-
Notifications
You must be signed in to change notification settings - Fork 655
Expand file tree
/
Copy pathsources-helpers.ts
More file actions
898 lines (787 loc) · 37.8 KB
/
sources-helpers.ts
File metadata and controls
898 lines (787 loc) · 37.8 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
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
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {assert} from 'chai';
import * as fs from 'node:fs';
import * as path from 'node:path';
import type * as puppeteer from 'puppeteer-core';
import {GEN_DIR} from '../../conductor/paths.js';
import type {DevToolsPage} from '../shared/frontend-helper.js';
import type {InspectedPage} from '../shared/target-helper.js';
import {openSoftContextMenuAndClickOnItem} from './context-menu-helpers.js';
import {veImpression} from './visual-logging-helpers.js';
export const ACTIVE_LINE = '.CodeMirror-activeline > pre > span';
export const PAUSE_BUTTON = '[aria-label="Pause script execution"]';
export const RESUME_BUTTON = '[aria-label="Resume script execution"]';
export const SOURCES_LINES_SELECTOR = '.CodeMirror-code > div';
export const PAUSE_INDICATOR_SELECTOR = '.paused-status';
export const CODE_LINE_COLUMN_SELECTOR = '.cm-lineNumbers';
export const CODE_LINE_SELECTOR = '.cm-lineNumbers .cm-gutterElement';
export const SCOPE_LOCAL_VALUES_SELECTOR = 'li[aria-label="Local"] + ol';
export const THREADS_SELECTOR = '[aria-label="Threads"]';
export const SELECTED_THREAD_SELECTOR = '.thread-item[aria-selected="true"] > div.thread-item-title';
export const STEP_INTO_BUTTON = '[aria-label="Step into next function call"]';
export const STEP_OVER_BUTTON = '[aria-label="Step over next function call"]';
export const STEP_OUT_BUTTON = '[aria-label="Step out of current function"]';
export const TURNED_ON_PAUSE_BUTTON_SELECTOR = 'button.toolbar-state-on';
export const DEBUGGER_PAUSED_EVENT = 'DevTools.DebuggerPaused';
const WATCH_EXPRESSION_VALUE_SELECTOR = '.watch-expression-tree-item .object-value-string.value';
export const OVERRIDES_TAB_SELECTOR = '[aria-label="Overrides"]';
export const ENABLE_OVERRIDES_SELECTOR = '[aria-label="Select folder for overrides"]';
const CLEAR_CONFIGURATION_SELECTOR = '[aria-label="Clear configuration"]';
export const PAUSE_ON_UNCAUGHT_EXCEPTION_SELECTOR = '.pause-on-uncaught-exceptions';
export const BREAKPOINT_ITEM_SELECTOR = '.breakpoint-item';
export async function getLineNumberElement(lineNumber: number|string, devToolsPage: DevToolsPage) {
return await devToolsPage.waitForFunction(async () => {
const visibleLines = await devToolsPage.$$(CODE_LINE_SELECTOR);
for (let i = 0; i < visibleLines.length; i++) {
const lineValue = await visibleLines[i].evaluate(node => (node as HTMLElement).innerText);
if (lineValue === `${lineNumber}`) {
return visibleLines[i];
}
}
return null;
});
}
export async function doubleClickSourceTreeItem(selector: string, devToolsPage: DevToolsPage) {
await devToolsPage.click(selector, {clickOptions: {clickCount: 2, offset: {x: 40, y: 10}}});
}
export async function waitForSourcesPanel(devToolsPage: DevToolsPage): Promise<void> {
// Wait for the navigation panel to show up
await devToolsPage.waitFor('.navigator-file-tree-item, .empty-state');
}
export async function openSourcesPanel(devToolsPage: DevToolsPage) {
// Locate the button for switching to the sources tab.
await devToolsPage.click('#tab-sources');
await waitForSourcesPanel(devToolsPage);
return await devToolsPage.waitForAria('sources');
}
export async function openFileInSourcesPanel(
testInput: string, devToolsPage: DevToolsPage, inspectedPage: InspectedPage) {
await inspectedPage.goToResource(`sources/${testInput}`);
await openSourcesPanel(devToolsPage);
}
export async function openSnippetsSubPane(devToolsPage: DevToolsPage) {
const root = await devToolsPage.waitFor('.navigator-tabbed-pane');
await devToolsPage.clickMoreTabsButton(root);
await devToolsPage.click('[aria-label="Snippets"]');
await devToolsPage.waitFor('[aria-label="New snippet"]');
}
/**
* Creates a new snippet, optionally pre-filling it with the provided content.
* `snippetName` must not contain spaces or special characters, otherwise
* `createNewSnippet` will time out.
* DevTools uses the escaped snippet name for the ARIA label. `createNewSnippet`
* doesn't mirror the escaping so it won't be able to wait for the snippet
* entry in the navigation tree to appear.
*/
export async function createNewSnippet(snippetName: string, content: string|undefined, devToolsPage: DevToolsPage) {
await devToolsPage.click('[aria-label="New snippet"]');
await devToolsPage.waitFor('[aria-label^="Script snippet"]');
await devToolsPage.typeText(snippetName);
await devToolsPage.pressKey('Enter');
await devToolsPage.waitFor(`[aria-label*="${snippetName}"]`);
if (content) {
await devToolsPage.pasteText(content);
await devToolsPage.pressKey('s', {control: true});
}
}
export async function openOverridesSubPane(devToolsPage: DevToolsPage) {
const root = await devToolsPage.waitFor('.navigator-tabbed-pane');
await devToolsPage.clickMoreTabsButton(root);
await devToolsPage.click('[aria-label="Overrides"]');
await devToolsPage.waitFor('[aria-label="Overrides panel"]');
}
export async function openFileInEditor(sourceFile: string, devToolsPage: DevToolsPage) {
await waitForSourceFiles(
SourceFileEvents.SOURCE_FILE_LOADED, files => files.some(f => f.endsWith(sourceFile)),
// Open a particular file in the editor
() => doubleClickSourceTreeItem(`[aria-label="${sourceFile}, file"]`, devToolsPage), devToolsPage);
}
export async function openSourceCodeEditorForFile(
sourceFile: string, testInput: string, devToolsPage: DevToolsPage, inspectedPage: InspectedPage) {
await openFileInSourcesPanel(testInput, devToolsPage, inspectedPage);
await openFileInEditor(sourceFile, devToolsPage);
}
export async function getBreakpointHitLocation(devToolsPage: DevToolsPage) {
const breakpointHitHandle = await devToolsPage.waitFor('.breakpoint-item.hit');
const locationHandle = await devToolsPage.waitFor('.location', breakpointHitHandle);
const locationText = await locationHandle.evaluate(location => location.textContent);
const groupHandle = await breakpointHitHandle.evaluateHandle(x => x.parentElement!);
const groupHeaderTitleHandle = await devToolsPage.waitFor('.group-header-title', groupHandle);
const groupHeaderTitle = await groupHeaderTitleHandle?.evaluate(header => header.textContent);
return `${groupHeaderTitle}:${locationText}`;
}
export async function getOpenSources(devToolsPage: DevToolsPage) {
const sourceTabPane = await devToolsPage.waitFor('#sources-panel-sources-view .tabbed-pane');
const sourceTabs = await devToolsPage.waitFor('.tabbed-pane-header-tabs', sourceTabPane);
const openSources =
await sourceTabs.$$eval('.tabbed-pane-header-tab', nodes => nodes.map(n => n.getAttribute('aria-label')));
return openSources;
}
export async function waitForHighlightedLine(lineNumber: number, devToolsPage: DevToolsPage) {
await devToolsPage.waitForFunction(async () => {
const selectedLine = await devToolsPage.waitFor('.cm-highlightedLine');
const currentlySelectedLineNumber = await selectedLine.evaluate(line => {
return [...line.parentElement?.childNodes || []].indexOf(line);
});
const lineNumbers = await devToolsPage.waitFor('.cm-lineNumbers');
const text = await lineNumbers.evaluate(
(node, lineNumber) => node.childNodes[lineNumber].textContent, currentlySelectedLineNumber + 1);
return Number(text) === lineNumber;
});
}
export async function getToolbarText(devToolsPage: DevToolsPage) {
const toolbar = await devToolsPage.waitFor('.sources-toolbar');
if (!toolbar) {
return [];
}
const textNodes = await devToolsPage.$$('.toolbar-text', toolbar);
return await Promise.all(textNodes.map(node => node.evaluate(node => node.textContent, node)));
}
export async function addBreakpointForLine(index: number|string, devToolsPage: DevToolsPage) {
await devToolsPage.waitForFunction(async () => !(await isBreakpointSet(index, devToolsPage)));
const breakpointLine = await getLineNumberElement(index, devToolsPage);
assert.isOk(breakpointLine);
await devToolsPage.clickElement(breakpointLine);
await devToolsPage.waitForFunction(async () => await isBreakpointSet(index, devToolsPage));
}
export async function removeBreakpointForLine(index: number|string, devToolsPage: DevToolsPage) {
await devToolsPage.waitForFunction(async () => await isBreakpointSet(index, devToolsPage));
const breakpointLine = await getLineNumberElement(index, devToolsPage);
assert.isOk(breakpointLine);
await devToolsPage.clickElement(breakpointLine);
await devToolsPage.waitForFunction(async () => !(await isBreakpointSet(index, devToolsPage)));
}
export async function addLogpointForLine(index: number, condition: string, devToolsPage: DevToolsPage) {
const breakpointLine = await getLineNumberElement(index, devToolsPage);
assert.isOk(breakpointLine);
await devToolsPage.waitForFunction(async () => !(await isBreakpointSet(index, devToolsPage)));
await devToolsPage.clickElement(breakpointLine, {clickOptions: {button: 'right'}});
await devToolsPage.click('aria/Add logpoint…');
const editDialog = await devToolsPage.waitFor('.sources-edit-breakpoint-dialog');
const conditionEditor = await devToolsPage.waitForAria('Code editor', editDialog);
await conditionEditor.focus();
await devToolsPage.typeText(condition);
await devToolsPage.pressKey('Enter');
await devToolsPage.waitForFunction(async () => await isBreakpointSet(index, devToolsPage));
}
export async function isBreakpointSet(lineNumber: number|string, devToolsPage: DevToolsPage) {
const lineNumberElement = await getLineNumberElement(lineNumber, devToolsPage);
const breakpointLineParentClasses = await lineNumberElement?.evaluate(n => n.className);
return breakpointLineParentClasses?.includes('cm-breakpoint');
}
/**
* @param lineNumber 1-based line number
* @param index 1-based index of the inline breakpoint in the given line
*/
export async function enableInlineBreakpointForLine(line: number, index: number, devToolsPage: DevToolsPage) {
const decorationSelector = `pierce/.cm-content > :nth-child(${line}) > :nth-child(${index} of .cm-inlineBreakpoint)`;
await devToolsPage.click(decorationSelector);
await devToolsPage.waitForFunction(
() => devToolsPage.page.$eval(
decorationSelector, element => !element.classList.contains('cm-inlineBreakpoint-disabled')));
}
/**
* @param lineNumber 1-based line number
* @param index 1-based index of the inline breakpoint in the given line
* @param expectNoBreakpoint If we should wait for the line to not have any inline breakpoints after
* the click instead of a disabled one.
*/
export async function disableInlineBreakpointForLine(
line: number, index: number, expectNoBreakpoint = false, devToolsPage: DevToolsPage) {
const decorationSelector = `pierce/.cm-content > :nth-child(${line}) > :nth-child(${index} of .cm-inlineBreakpoint)`;
await devToolsPage.click(decorationSelector);
if (expectNoBreakpoint) {
await devToolsPage.waitForFunction(
() => devToolsPage.page.$$eval(
`pierce/.cm-content > :nth-child(${line}) > .cm-inlineBreakpoint`, elements => elements.length === 0));
} else {
await devToolsPage.waitForFunction(
() => devToolsPage.page.$eval(
decorationSelector, element => element.classList.contains('cm-inlineBreakpoint-disabled')));
}
}
export async function checkBreakpointDidNotActivate(devToolsPage: DevToolsPage) {
// TODO(almuthanna): make sure this check happens at a point where the pause indicator appears if it was active
// TODO: it should actually wait for rendering to finish.
await devToolsPage.drainTaskQueue();
await devToolsPage.waitForNone(PAUSE_INDICATOR_SELECTOR);
}
export async function getBreakpointDecorators(disabledOnly = false, expected = 0, devToolsPage: DevToolsPage) {
const selector = `.cm-breakpoint${disabledOnly ? '-disabled' : ''}`;
const breakpointDecorators = await devToolsPage.waitForMany(selector, expected);
return await Promise.all(
breakpointDecorators.map(breakpointDecorator => breakpointDecorator.evaluate(n => Number(n.textContent))));
}
export async function getNonBreakableLines(devToolsPage: DevToolsPage) {
const selector = '.cm-nonBreakableLine';
await devToolsPage.waitFor(selector);
const unbreakableLines = await devToolsPage.$$(selector);
return await Promise.all(
unbreakableLines.map(unbreakableLine => unbreakableLine.evaluate(n => Number(n.textContent))));
}
export async function executionLineHighlighted(devToolsPage: DevToolsPage) {
return await devToolsPage.waitFor('.cm-executionLine');
}
export async function getCallFrameNames(devToolsPage: DevToolsPage) {
const selector = '.call-frame-item:not(.hidden) .call-frame-item-title';
await devToolsPage.waitFor(selector);
const items = await devToolsPage.$$(selector);
const promises = items.map(handle => handle.evaluate(el => el.textContent as string));
const results = [];
for (const promise of promises) {
results.push(await promise);
}
return results;
}
export async function getCallFrameLocations(devToolsPage: DevToolsPage) {
const selector = '.call-frame-item:not(.hidden) .call-frame-location';
await devToolsPage.waitFor(selector);
const items = await devToolsPage.$$(selector);
const promises = items.map(handle => handle.evaluate(el => el.textContent as string));
const results = [];
for (const promise of promises) {
results.push(await promise);
}
return results;
}
export async function switchToCallFrame(index: number, devToolsPage: DevToolsPage) {
const selector = `.call-frame-item[aria-posinset="${index}"]`;
await devToolsPage.click(selector);
await devToolsPage.waitFor(selector + '[aria-selected="true"]');
}
export async function retrieveTopCallFrameScriptLocation(
script: string, target: puppeteer.Page|InspectedPage, devToolsPage: DevToolsPage) {
// The script will run into a breakpoint, which means that it will not actually
// finish the evaluation, until we continue executing.
// Thus, we have to await it at a later point, while stepping through the code.
const scriptEvaluation = target.evaluate(script);
// Wait for the evaluation to be paused and shown in the UI
// and retrieve the top level call frame script location name
const scriptLocation = await retrieveTopCallFrameWithoutResuming(devToolsPage);
// Resume the evaluation
await devToolsPage.click(RESUME_BUTTON);
// Make sure to await the context evaluate before asserting
// Otherwise the Puppeteer process might crash on a failure assertion,
// as its execution context is destroyed
await scriptEvaluation;
return scriptLocation;
}
export async function retrieveTopCallFrameWithoutResuming(devToolsPage: DevToolsPage) {
// Wait for the evaluation to be paused and shown in the UI
await devToolsPage.waitFor(PAUSE_INDICATOR_SELECTOR);
// Retrieve the top level call frame script location name
const locationHandle = await devToolsPage.waitFor('.call-frame-location');
const scriptLocation = await locationHandle.evaluate(location => location.textContent);
return scriptLocation;
}
export async function waitForStackTopMatch(matcher: RegExp, devToolsPage: DevToolsPage) {
// The call stack is updated asynchronously, so let us wait until we see the correct one
// (or report the last one we have seen before timeout).
let stepLocation = '<no call stack>';
await devToolsPage.waitForFunctionWithTries(async () => {
stepLocation = await retrieveTopCallFrameWithoutResuming(devToolsPage) ?? '<invalid>';
return stepLocation?.match(matcher);
}, {tries: 10});
return stepLocation;
}
export async function waitForNewLocation(oldLocation: string, devToolsPage: DevToolsPage) {
// The call stack is updated asynchronously, so let us wait until we see the correct one
// (or report the last one we have seen before timeout).
let stepLocation = '<no call stack>';
await devToolsPage.waitForFunction(async () => {
stepLocation = await retrieveTopCallFrameWithoutResuming(devToolsPage) ?? '<invalid>';
return stepLocation && stepLocation !== oldLocation;
});
return stepLocation;
}
export async function setEventListenerBreakpoint(groupName: string, eventName: string, devToolsPage: DevToolsPage) {
const eventListenerBreakpointsSection = await devToolsPage.waitForAria('Event Listener Breakpoints');
const expanded = await eventListenerBreakpointsSection.evaluate(el => el.getAttribute('aria-expanded'));
if (expanded !== 'true') {
await devToolsPage.click('[aria-label="Event Listener Breakpoints"]');
await devToolsPage.waitFor('[aria-label="Event Listener Breakpoints"][aria-expanded="true"]');
}
const eventSelector = `input[type="checkbox"][title="${eventName}"]`;
const groupSelector = `input[type="checkbox"][title="${groupName}"]`;
const groupCheckbox = await devToolsPage.waitFor(groupSelector);
await devToolsPage.scrollElementIntoView(groupSelector);
await devToolsPage.waitForVisible(groupSelector);
const eventCheckbox = await devToolsPage.$(eventSelector);
if (!eventCheckbox || !(await eventCheckbox.evaluate(x => x.checkVisibility()))) {
// Unfortunately the shadow DOM makes it hard to find the expander element
// we are attempting to click on, so we click to the left of the checkbox
// bounding box.
const rectData = await groupCheckbox.evaluate(element => {
const {left, top, width, height} = element.getBoundingClientRect();
return {left, top, width, height};
});
await devToolsPage.page.mouse.click(rectData.left - 10, rectData.top + rectData.height * .5);
await devToolsPage.waitForVisible(eventSelector);
}
await devToolsPage.setCheckBox(eventSelector, true);
}
declare global {
interface Window {
/* eslint-disable @typescript-eslint/naming-convention */
__sourceFileEvents: Map<number, {files: string[], handler: (e: Event) => void}>;
/* eslint-enable @typescript-eslint/naming-convention */
}
}
export const enum SourceFileEvents {
SOURCE_FILE_LOADED = 'source-file-loaded',
ADDED_TO_SOURCE_TREE = 'source-tree-file-added',
}
let nextEventHandlerId = 0;
export async function waitForSourceFiles<T>(
eventName: SourceFileEvents, waitCondition: (files: string[]) => boolean | Promise<boolean>, action: () => T,
devToolsPage: DevToolsPage): Promise<T> {
const eventHandlerId = nextEventHandlerId++;
// Install new listener for the event
await devToolsPage.evaluate((eventName, eventHandlerId) => {
if (!window.__sourceFileEvents) {
window.__sourceFileEvents = new Map();
}
const handler = (event: Event) => {
const {detail} = event as CustomEvent<string>;
if (!detail.includes('pptr:')) {
window.__sourceFileEvents.get(eventHandlerId)?.files.push(detail);
}
};
window.__sourceFileEvents.set(eventHandlerId, {files: [], handler});
window.addEventListener(eventName, handler);
}, eventName, eventHandlerId);
const result = await action();
await devToolsPage.waitForFunction(async logger => {
const files = await devToolsPage.evaluate(
eventHandlerId => window.__sourceFileEvents.get(eventHandlerId)?.files, eventHandlerId);
assert.isOk(files);
logger.log(`Checking ${files.length} files`);
return await waitCondition(files);
}, undefined, 'Waiting for source files to match condition');
await devToolsPage.evaluate((eventName, eventHandlerId) => {
const handler = window.__sourceFileEvents.get(eventHandlerId);
if (!handler) {
throw new Error('handler unexpectedly unregistered');
}
window.__sourceFileEvents.delete(eventHandlerId);
window.removeEventListener(eventName, handler.handler);
}, eventName, eventHandlerId);
return result;
}
export async function captureAddedSourceFiles(
count: number, action: () => Promise<void>, devToolsPage: DevToolsPage): Promise<string[]> {
let capturedFileNames!: string[];
await waitForSourceFiles(SourceFileEvents.ADDED_TO_SOURCE_TREE, files => {
capturedFileNames = files;
return files.length >= count;
}, action, devToolsPage);
return capturedFileNames.map(f => new URL(`http://${f}`).pathname);
}
export async function reloadPageAndWaitForSourceFile(
sourceFile: string, devToolsPage: DevToolsPage, inspectedPage: InspectedPage) {
await waitForSourceFiles(
SourceFileEvents.SOURCE_FILE_LOADED, files => files.some(f => f.endsWith(sourceFile)),
() => inspectedPage.reload(), devToolsPage);
}
export function isEqualOrAbbreviation(abbreviated: string, full: string): boolean {
const split = abbreviated.split('…');
if (split.length === 1) {
return abbreviated === full;
}
assert.lengthOf(split, 2);
return full.startsWith(split[0]) && full.endsWith(split[1]);
}
/** Helpers for navigating the file tree. **/
export interface NestedFileSelector {
rootSelector: string;
domainSelector: string;
folderSelector?: string;
fileSelector: string;
}
export function createSelectorsForWorkerFile(
workerName: string, folderName: string, fileName: string, workerIndex = 1,
inspectedPage: InspectedPage): NestedFileSelector {
const rootSelector = new Array(workerIndex).fill(`[aria-label="${workerName}, worker"]`).join(' ~ ');
const domainSelector = `${rootSelector} + ol > [aria-label="localhost:${inspectedPage.serverPort}, domain"]`;
const folderSelector = `${domainSelector} + ol > [aria-label^="${folderName}, "]`;
const fileSelector = `${folderSelector} + ol > [aria-label="${fileName}, file"]`;
return {
rootSelector,
domainSelector,
folderSelector,
fileSelector,
};
}
async function isExpanded(sourceTreeItem: puppeteer.ElementHandle<Element>): Promise<boolean> {
return await sourceTreeItem.evaluate(element => {
return element.getAttribute('aria-expanded') === 'true';
});
}
export async function expandSourceTreeItem(selector: string, devToolsPage: DevToolsPage) {
// FIXME(crbug/1112692): Refactor test to remove the timeout.
await devToolsPage.timeout(50);
const sourceTreeItem = await devToolsPage.waitFor(selector);
if (!await isExpanded(sourceTreeItem)) {
// FIXME(crbug/1112692): Refactor test to remove the timeout.
await devToolsPage.timeout(50);
await doubleClickSourceTreeItem(selector, devToolsPage);
}
}
export async function expandFileTree(selectors: NestedFileSelector, devToolsPage: DevToolsPage) {
await expandSourceTreeItem(selectors.rootSelector, devToolsPage);
await expandSourceTreeItem(selectors.domainSelector, devToolsPage);
if (selectors.folderSelector) {
await expandSourceTreeItem(selectors.folderSelector, devToolsPage);
}
// FIXME(crbug/1112692): Refactor test to remove the timeout.
await devToolsPage.timeout(50);
return await devToolsPage.waitFor(selectors.fileSelector);
}
export async function readSourcesTreeView(devToolsPage: DevToolsPage): Promise<string[]> {
const items = await devToolsPage.$$('.navigator-folder-tree-item,.navigator-file-tree-item');
const promises = items.map(handle => handle.evaluate(el => el.textContent as string));
const results = await Promise.all(promises);
return results.map(item => item.replace(/localhost:[0-9]+/, 'localhost:XXXX'));
}
export async function readIgnoreListedSources(devToolsPage: DevToolsPage): Promise<string[]> {
const items =
await devToolsPage.$$('.navigator-folder-tree-item.is-ignore-listed,.navigator-file-tree-item.is-ignore-listed');
const promises = items.map(handle => handle.evaluate(el => el.textContent as string));
const results = await Promise.all(promises);
return results.map(item => item.replace(/localhost:[0-9]+/, 'localhost:XXXX'));
}
async function hasPausedEvents(devToolsPage: DevToolsPage): Promise<boolean> {
const events = await devToolsPage.getPendingEvents(DEBUGGER_PAUSED_EVENT);
return Boolean(events?.length);
}
export async function stepThroughTheCode(devToolsPage: DevToolsPage, checkLineChange = true) {
const currentLocation = checkLineChange ? await retrieveTopCallFrameWithoutResuming(devToolsPage) : '';
await devToolsPage.getPendingEvents(DEBUGGER_PAUSED_EVENT);
await devToolsPage.pressKey('F9');
await devToolsPage.waitForFunction(() => hasPausedEvents(devToolsPage));
await devToolsPage.waitFor(PAUSE_INDICATOR_SELECTOR);
if (checkLineChange) {
await waitForNewLocation(currentLocation, devToolsPage);
}
}
export async function stepIn(devToolsPage: DevToolsPage, checkLineChange = true) {
const currentLocation = checkLineChange ? await retrieveTopCallFrameWithoutResuming(devToolsPage) : '';
await devToolsPage.getPendingEvents(DEBUGGER_PAUSED_EVENT);
await devToolsPage.pressKey('F11');
await devToolsPage.waitForFunction(() => hasPausedEvents(devToolsPage));
await devToolsPage.waitFor(PAUSE_INDICATOR_SELECTOR);
if (checkLineChange) {
await waitForNewLocation(currentLocation, devToolsPage);
}
}
export async function stepOver(devToolsPage: DevToolsPage, checkLineChange = true) {
const currentLocation = checkLineChange ? await retrieveTopCallFrameWithoutResuming(devToolsPage) : '';
await devToolsPage.getPendingEvents(DEBUGGER_PAUSED_EVENT);
await devToolsPage.pressKey('F10');
await devToolsPage.waitForFunction(() => hasPausedEvents(devToolsPage));
await devToolsPage.waitFor(PAUSE_INDICATOR_SELECTOR);
if (checkLineChange) {
await waitForNewLocation(currentLocation, devToolsPage);
}
}
export async function stepOut(devToolsPage: DevToolsPage, checkLineChange = true) {
const currentLocation = checkLineChange ? await retrieveTopCallFrameWithoutResuming(devToolsPage) : '';
await devToolsPage.getPendingEvents(DEBUGGER_PAUSED_EVENT);
await devToolsPage.pressKey('F11', {shift: true});
await devToolsPage.waitForFunction(() => hasPausedEvents(devToolsPage));
await devToolsPage.waitFor(PAUSE_INDICATOR_SELECTOR);
if (checkLineChange) {
await waitForNewLocation(currentLocation, devToolsPage);
}
}
export async function openNestedWorkerFile(selectors: NestedFileSelector, devToolsPage: DevToolsPage) {
await expandFileTree(selectors, devToolsPage);
// FIXME(crbug/1112692): Refactor test to remove the timeout.
await devToolsPage.timeout(50);
await devToolsPage.click(selectors.fileSelector);
}
export async function inspectMemory(variableName: string, devToolsPage: DevToolsPage) {
await openSoftContextMenuAndClickOnItem(
`[data-object-property-name-for-test="${variableName}"]`,
'Open in Memory inspector panel',
devToolsPage,
);
}
export async function getScopeNames(devToolsPage: DevToolsPage) {
const scopeElements = await devToolsPage.$$('.scope-chain-sidebar-pane-section-title');
const scopeNames = await Promise.all(scopeElements.map(nodes => nodes.evaluate(n => n.textContent)));
return scopeNames;
}
export async function getValuesForScope(
scope: string, expandCount: number, waitForNoOfValues: number, devToolsPage: DevToolsPage) {
const scopeSelector = `[aria-label="${scope}"]`;
await devToolsPage.waitFor(scopeSelector);
for (let i = 0; i < expandCount; i++) {
await devToolsPage.click(`${scopeSelector} + ol li[aria-expanded=false]`);
}
const valueSelector = `${scopeSelector} + ol .name-and-value`;
async function readValues() {
const valueSelectorElements = await devToolsPage.waitForMany(valueSelector, waitForNoOfValues);
return await Promise.all(valueSelectorElements.map(elem => elem.evaluate(n => n.textContent as string)));
}
let previousValues = await readValues();
return await devToolsPage.waitForFunction(async function() {
const values = await readValues();
if (values.join('') === previousValues.join('')) {
return values;
}
previousValues = values;
return;
});
}
export async function waitValuesForScope(
scope: string, expandCount: number, expectedValues: string[], devToolsPage: DevToolsPage): Promise<string[]> {
await devToolsPage.waitForFunction(async () => {
const values = await getValuesForScope(scope, expandCount, expectedValues.length, devToolsPage);
return values.every((value, i) => value === expectedValues[i]);
});
return expectedValues;
}
export async function getPausedMessages(devToolsPage: DevToolsPage) {
const messageElement = await devToolsPage.page.waitForSelector('.paused-message');
assert.isOk(messageElement, 'getPausedMessages: did not find .paused-message element.');
const statusMain = await devToolsPage.waitFor('.status-main', messageElement);
const statusSub = await devToolsPage.waitFor('.status-sub', messageElement);
return {
statusMain: await statusMain.evaluate(x => x.textContent),
statusSub: await statusSub.evaluate(x => x.textContent),
};
}
export async function getWatchExpressionsValues(devToolsPage: DevToolsPage) {
await devToolsPage.waitForFunction(async () => {
const expandedOption = await devToolsPage.$('.watch-expression-title');
if (expandedOption) {
return true;
}
await devToolsPage.click('[aria-label="Watch"]');
// Wait for the click event to settle.
await devToolsPage.timeout(100);
return expandedOption !== null;
});
await devToolsPage.pressKey('ArrowRight');
const watchExpressionValue = await devToolsPage.$(WATCH_EXPRESSION_VALUE_SELECTOR);
if (!watchExpressionValue) {
return null;
}
const values = await devToolsPage.$$(WATCH_EXPRESSION_VALUE_SELECTOR) as Array<puppeteer.ElementHandle<HTMLElement>>;
return await Promise.all(values.map(value => value.evaluate(element => element.innerText)));
}
export async function runSnippet(devToolsPage: DevToolsPage) {
await devToolsPage.pressKey('Enter', {control: true});
}
export async function evaluateSelectedTextInConsole(devToolsPage: DevToolsPage) {
await devToolsPage.pressKey('E', {control: true, shift: true});
// TODO: it should actually wait for rendering to finish. Note: it is
// drained three times because rendering currently takes 3 dependent
// tasks to finish.
await devToolsPage.drainTaskQueue();
await devToolsPage.drainTaskQueue();
await devToolsPage.drainTaskQueue();
}
export async function addSelectedTextToWatches(devToolsPage: DevToolsPage) {
await devToolsPage.pressKey('A', {control: true, shift: true});
}
export async function enableLocalOverrides(devToolsPage: DevToolsPage) {
await openOverridesSubPane(devToolsPage);
await devToolsPage.click(ENABLE_OVERRIDES_SELECTOR);
await devToolsPage.waitFor(CLEAR_CONFIGURATION_SELECTOR);
}
export interface LabelMapping {
label: string;
moduleOffset: number;
bytecode: number;
sourceLine: number;
labelLine: number;
labelColumn: number;
}
export class WasmLocationLabels {
readonly #mappings: Map<string, LabelMapping[]>;
readonly #source: string;
readonly #wasm: string;
readonly #devToolsPage: DevToolsPage;
readonly #inspectedPage: InspectedPage;
constructor(
source: string, wasm: string, mappings: Map<string, LabelMapping[]>, devToolsPage: DevToolsPage,
inspectedPage: InspectedPage) {
this.#mappings = mappings;
this.#source = source;
this.#wasm = wasm;
this.#devToolsPage = devToolsPage;
this.#inspectedPage = inspectedPage;
}
static load(source: string, wasm: string, devToolsPage: DevToolsPage, inspectedPage: InspectedPage):
WasmLocationLabels {
const mapFileName = path.join(GEN_DIR, 'test', 'e2e', 'resources', `${wasm}.map.json`);
const mapFile = JSON.parse(fs.readFileSync(mapFileName, {encoding: 'utf-8'})) as Array<{
source: string,
generatedLine: number,
generatedColumn: number,
bytecodeOffset: number,
originalLine: number,
originalColumn: number,
}>;
const sourceFileName = path.join(GEN_DIR, 'test', 'e2e', 'resources', source);
const sourceFile = fs.readFileSync(sourceFileName, {encoding: 'utf-8'});
const labels = new Map<string, number>();
for (const [index, line] of sourceFile.split('\n').entries()) {
if (line.trim().startsWith(';;@')) {
const label = line.trim().substr(3).trim();
assert.isFalse(labels.has(label), `Label ${label} must be unique`);
labels.set(label, index + 1);
}
}
const mappings = new Map<string, LabelMapping[]>();
for (const m of mapFile) {
const entry = mappings.get(m.source) ?? [];
if (entry.length === 0) {
mappings.set(m.source, entry);
}
const labelLine = m.originalLine;
const labelColumn = m.originalColumn;
const sourceLine = labels.get(`${m.source}:${labelLine}:${labelColumn}`);
assert.isOk(sourceLine);
entry.push({
label: m.source,
moduleOffset: m.generatedColumn,
bytecode: m.bytecodeOffset,
sourceLine,
labelLine,
labelColumn,
});
}
return new WasmLocationLabels(source, wasm, mappings, devToolsPage, inspectedPage);
}
async checkLocationForLabel(label: string) {
const pauseLocation = await retrieveTopCallFrameWithoutResuming(this.#devToolsPage);
const pausedLine = this.#mappings.get(label)!.find(
line => pauseLocation === `${path.basename(this.#wasm)}:0x${line.moduleOffset.toString(16)}` ||
pauseLocation === `${path.basename(this.#source)}:${line.sourceLine}`);
assert.isOk(pausedLine);
return pausedLine;
}
async addBreakpointsForLabelInSource(label: string) {
await openFileInEditor(path.basename(this.#source), this.#devToolsPage);
await Promise.all(
this.#mappings.get(label)!.map(({sourceLine}) => addBreakpointForLine(sourceLine, this.#devToolsPage)));
}
async addBreakpointsForLabelInWasm(label: string) {
await openFileInEditor(path.basename(this.#wasm), this.#devToolsPage);
const visibleLines = await this.#devToolsPage.$$(CODE_LINE_SELECTOR);
const lineNumbers = await Promise.all(visibleLines.map(line => line.evaluate(node => node.textContent)));
const lineNumberLabels = new Map(lineNumbers.map(label => [Number(label), label]));
await Promise.all(this.#mappings.get(label)!.map(
({moduleOffset}) => addBreakpointForLine(lineNumberLabels.get(moduleOffset)!, this.#devToolsPage)));
}
async setBreakpointInSourceAndRun(label: string, script: string) {
await this.addBreakpointsForLabelInSource(label);
void this.#inspectedPage.evaluate(script);
await this.checkLocationForLabel(label);
}
async setBreakpointInWasmAndRun(label: string, script: string) {
await this.addBreakpointsForLabelInWasm(label);
void this.#inspectedPage.evaluate(script);
await this.checkLocationForLabel(label);
}
async continueAndCheckForLabel(label: string) {
await this.#devToolsPage.click(RESUME_BUTTON);
await this.checkLocationForLabel(label);
}
getMappingsForPlugin(): LabelMapping[] {
return Array.from(this.#mappings.values()).flat();
}
}
export async function retrieveCodeMirrorEditorContent(devToolsPage: DevToolsPage): Promise<string[]> {
const editor = await devToolsPage.waitFor('[aria-label="Code editor"]');
return await editor.evaluate(
node => [...node.querySelectorAll('.cm-line')].map(node => node.textContent || '') || []);
}
export async function waitForLines(lineCount: number, devToolsPage: DevToolsPage): Promise<void> {
await devToolsPage.waitFor(new Array(lineCount).fill('.cm-line').join(' ~ '));
}
export async function isPrettyPrinted(devToolsPage: DevToolsPage): Promise<boolean> {
const prettyButton = await devToolsPage.waitFor('[title="Pretty print"]');
const isPretty = await prettyButton.evaluate(e => e.classList.contains('toggled'));
return isPretty === true;
}
export function veImpressionForSourcesPanel() {
return veImpression('Panel', 'sources', [
veImpression(
'Toolbar', 'debug',
[
veImpression('Toggle', 'debugger.toggle-pause'),
veImpression('Action', 'debugger.step-over'),
veImpression('Action', 'debugger.step-into'),
veImpression('Action', 'debugger.step-out'),
veImpression('Action', 'debugger.step'),
veImpression('Toggle', 'debugger.toggle-breakpoints-active'),
]),
veImpression(
'Pane', 'debug',
[
veImpression('SectionHeader', 'sources.watch'),
veImpression('SectionHeader', 'sources.js-breakpoints'),
veImpression('SectionHeader', 'sources.scope-chain'),
veImpression('SectionHeader', 'sources.callstack'),
veImpression('SectionHeader', 'sources.xhr-breakpoints'),
veImpression('SectionHeader', 'sources.dom-breakpoints'),
veImpression('SectionHeader', 'sources.global-listeners'),
veImpression('SectionHeader', 'sources.event-listener-breakpoints'),
veImpression('SectionHeader', 'sources.csp-violation-breakpoints'),
veImpression('Section', 'sources.scope-chain'),
veImpression('Section', 'sources.callstack'),
veImpression(
'Section', 'sources.js-breakpoints',
[
veImpression('Toggle', 'pause-uncaught'),
veImpression('Toggle', 'pause-on-caught-exception'),
]),
]),
veImpression(
'Pane', 'editor',
[
veImpression('Toolbar', 'bottom'),
veImpression(
'Toolbar', 'top',
[
veImpression('ToggleSubpane', 'navigator'),
veImpression('ToggleSubpane', 'debugger'),
]),
]),
veImpression(
'Toolbar', 'navigator',
[
veImpression('DropDown', 'more-tabs'),
veImpression('PanelTabHeader', 'navigator-network'),
veImpression('PanelTabHeader', 'navigator-files'),
veImpression('DropDown', 'more-options'),
]),
veImpression(
'Pane', 'navigator-network',
[
veImpression(
'Tree', undefined,
[
veImpression(
'TreeItem', 'frame',
[
veImpression('Expand'),
veImpression(
'TreeItem', 'domain',
[
veImpression('Expand'),
veImpression('TreeItem', 'document', [
veImpression('Value', 'title'),
]),
]),
]),
]),
]),
]);
}