Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore: reverse recorder <-> recorder app dep (#36544)
Pavel Feldman80f93258aa58
diff --git a/packages/playwright-core/src/server/browserContext.ts b/packages/playwright-core/src/server/browserContext.tsindex f62a0963f5..f53e40d5ba 100644--- a/packages/playwright-core/src/server/browserContext.ts+++ b/packages/playwright-core/src/server/browserContext.ts@@ -132,7 +132,7 @@ export abstract class BrowserContext extends SdkObject {// When paused, show inspector.if (this._debugger.isPaused())- await RecorderApp.showInspectorNoReply(this);+ RecorderApp.showInspectorNoReply(this);this._debugger.on(Debugger.Events.PausedStateChanged, () => {if (this._debugger.isPaused())diff --git a/packages/playwright-core/src/server/debugController.ts b/packages/playwright-core/src/server/debugController.tsindex dba94b6427..81d400eb9e 100644--- a/packages/playwright-core/src/server/debugController.ts+++ b/packages/playwright-core/src/server/debugController.ts@@ -16,11 +16,10 @@import { SdkObject, createInstrumentation } from './instrumentation';import { gracefullyProcessExitDoNotHang } from './utils/processLauncher';-import { Recorder } from './recorder';+import { Recorder, RecorderEvent } from './recorder';import { asLocator } from '../utils';import { parseAriaSnapshotUnsafe } from '../utils/isomorphic/ariaSnapshot';import { yaml } from '../utilsBundle';-import { EmptyRecorderApp } from './recorder/recorderApp';import { unsafeLocatorOrSelectorAsSelector } from '../utils/isomorphic/locatorParser';import { generateCode } from './codegen/language';import { collapseActions } from './recorder/recorderUtils';@@ -129,7 +128,7 @@ export class DebugController extends SdkObject {if (ariaTemplate)recorder.setHighlightedAriaTemplate(ariaTemplate);else if (params.selector)- recorder.setHighlightedSelector(this._sdkLanguage, params.selector);+ recorder.setHighlightedSelector(params.selector);}}@@ -169,8 +168,11 @@ export class DebugController extends SdkObject {const contexts = new Set<BrowserContext>();for (const page of this._playwright.allPages())contexts.add(page.browserContext);- const result = await Promise.all([...contexts].map(c => Recorder.showInspector(c, { omitCallTracking: true }, () => Promise.resolve(new InspectingRecorderApp(this)))));- return result.filter(Boolean) as Recorder[];+ const recorders = await Promise.all([...contexts].map(c => Recorder.forContext(c, { omitCallTracking: true })));+ const nonNullRecorders = recorders.filter(Boolean) as Recorder[];+ for (const recorder of recorders)+ wireListeners(recorder, this);+ return nonNullRecorders;}private async _closeBrowsersWithoutPages() {@@ -185,49 +187,44 @@ export class DebugController extends SdkObject {}}-class InspectingRecorderApp extends EmptyRecorderApp {- private _debugController: DebugController;- private _actions: actions.ActionInContext[] = [];- private _languageGenerator: JavaScriptLanguageGenerator;+const wiredSymbol = Symbol('wired');- constructor(debugController: DebugController) {- super();- this._debugController = debugController;- this._languageGenerator = new JavaScriptLanguageGenerator(/* isPlaywrightTest */true);- }+function wireListeners(recorder: Recorder, debugController: DebugController) {+ if ((recorder as any)[wiredSymbol])+ return;+ (recorder as any)[wiredSymbol] = true;- override async elementPicked(elementInfo: ElementInfo): Promise<void> {- const locator: string = asLocator(this._debugController._sdkLanguage, elementInfo.selector);- this._debugController.emit(DebugController.Events.InspectRequested, { selector: elementInfo.selector, locator, ariaSnapshot: elementInfo.ariaSnapshot });- }+ const actions: actions.ActionInContext[] = [];+ const languageGenerator = new JavaScriptLanguageGenerator(/* isPlaywrightTest */true);- override async setPaused(paused: boolean) {- this._debugController.emit(DebugController.Events.Paused, { paused });- }-- override async setMode(mode: Mode) {- this._debugController.emit(DebugController.Events.SetModeRequested, { mode });- }-- override async actionAdded(action: actions.ActionInContext): Promise<void> {- this._actions.push(action);- this._actionsChanged();- }-- override async signalAdded(signal: actions.Signal): Promise<void> {- const lastAction = this._actions[this._actions.length - 1];- if (lastAction)- lastAction.action.signals.push(signal);- this._actionsChanged();- }-- private _actionsChanged() {- const actions = collapseActions(this._actions);- const { header, footer, text, actionTexts } = generateCode(actions, this._languageGenerator, {+ const actionsChanged = () => {+ const aa = collapseActions(actions);+ const { header, footer, text, actionTexts } = generateCode(aa, languageGenerator, {browserName: 'chromium',launchOptions: {},contextOptions: {},});- this._debugController.emit(DebugController.Events.SourceChanged, { text, header, footer, actions: actionTexts });- }+ debugController.emit(DebugController.Events.SourceChanged, { text, header, footer, actions: actionTexts });+ };++ recorder.on(RecorderEvent.ElementPicked, (elementInfo: ElementInfo) => {+ const locator: string = asLocator(debugController._sdkLanguage, elementInfo.selector);+ debugController.emit(DebugController.Events.InspectRequested, { selector: elementInfo.selector, locator, ariaSnapshot: elementInfo.ariaSnapshot });+ });+ recorder.on(RecorderEvent.PausedStateChanged, (paused: boolean) => {+ debugController.emit(DebugController.Events.Paused, { paused });+ });+ recorder.on(RecorderEvent.ModeChanged, (mode: Mode) => {+ debugController.emit(DebugController.Events.SetModeRequested, { mode });+ });+ recorder.on(RecorderEvent.ActionAdded, (action: actions.ActionInContext) => {+ actions.push(action);+ actionsChanged();+ });+ recorder.on(RecorderEvent.SignalAdded, (signal: actions.Signal) => {+ const lastAction = actions[actions.length - 1];+ if (lastAction)+ lastAction.action.signals.push(signal);+ actionsChanged();+ });}diff --git a/packages/playwright-core/src/server/recorder.ts b/packages/playwright-core/src/server/recorder.tsindex 3866475289..8d5d995dcb 100644--- a/packages/playwright-core/src/server/recorder.ts+++ b/packages/playwright-core/src/server/recorder.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import EventEmitter from 'events';import fs from 'fs';import { isUnderTest } from '../utils';@@ -31,15 +32,13 @@ import { Frame } from './frames';import { Page } from './page';import { performAction } from './recorder/recorderRunner';-import type { Language } from './codegen/types';import type { CallMetadata, InstrumentationListener, SdkObject } from './instrumentation';-import type { IRecorder, IRecorderApp, IRecorderAppFactory } from './recorder/recorderFrontend';import type { Point } from '../utils/isomorphic/types';import type { AriaTemplateNode } from '@isomorphic/ariaSnapshot';import type * as channels from '@protocol/channels';import type * as actions from '@recorder/actions';-import type { CallLog, CallLogStatus, ElementInfo, EventData, Mode, OverlayState, Source, UIState } from '@recorder/recorderTypes';+import type { CallLog, CallLogStatus, ElementInfo, Mode, OverlayState, Source, UIState } from '@recorder/recorderTypes';import type { RegisteredListener } from '../utils';import type { Signal } from '../../../recorder/src/actions';@@ -47,14 +46,37 @@ const recorderSymbol = Symbol('recorderSymbol');type BindingSource = { frame: Frame, page: Page };-export class Recorder implements InstrumentationListener, IRecorder {+export const RecorderEvent = {+ PausedStateChanged: 'pausedStateChanged',+ ModeChanged: 'modeChanged',+ ElementPicked: 'elementPicked',+ CallLogsUpdated: 'callLogsUpdated',+ UserSourcesChanged: 'userSourcesChanged',+ ActionAdded: 'actionAdded',+ SignalAdded: 'signalAdded',+ PageNavigated: 'pageNavigated',+ ContextClosed: 'contextClosed',+} as const;++export type RecorderEventMap = {+ [RecorderEvent.PausedStateChanged]: [paused: boolean];+ [RecorderEvent.ModeChanged]: [mode: Mode];+ [RecorderEvent.ElementPicked]: [elementInfo: ElementInfo, userGesture?: boolean];+ [RecorderEvent.CallLogsUpdated]: [callLogs: CallLog[]];+ [RecorderEvent.UserSourcesChanged]: [sources: Source[]];+ [RecorderEvent.ActionAdded]: [action: actions.ActionInContext];+ [RecorderEvent.SignalAdded]: [signal: actions.Signal];+ [RecorderEvent.PageNavigated]: [url: string];+ [RecorderEvent.ContextClosed]: [];+};++export class Recorder extends EventEmitter<RecorderEventMap> implements InstrumentationListener {readonly handleSIGINT: boolean | undefined;private _context: BrowserContext;private _params: channels.BrowserContextEnableRecorderParams;private _mode: Mode;private _highlightedElement: { selector?: string, ariaTemplate?: AriaTemplateNode } = {};private _overlayState: OverlayState = { offsetX: 0 };- private _recorderApp: IRecorderApp | null = null;private _currentCallsMetadata = new Map<CallMetadata, SdkObject>();private _userSources = new Map<string, Source>();private _debugger: Debugger;@@ -69,29 +91,25 @@ export class Recorder implements InstrumentationListener, IRecorder {private _lastDownloadOrdinal = -1;private _listeners: RegisteredListener[] = [];private _enabled: boolean = false;+ private _callLogs: CallLog[] = [];- static async showInspector(context: BrowserContext, params: channels.BrowserContextEnableRecorderParams, recorderAppFactory: IRecorderAppFactory) {- return await Recorder.show(context, recorderAppFactory, params);- }-- static show(context: BrowserContext, recorderAppFactory: IRecorderAppFactory, params: channels.BrowserContextEnableRecorderParams): Promise<Recorder> {+ static forContext(context: BrowserContext, params: channels.BrowserContextEnableRecorderParams): Promise<Recorder> {let recorderPromise = (context as any)[recorderSymbol] as Promise<Recorder>;if (!recorderPromise) {- recorderPromise = Recorder._create(context, recorderAppFactory, params);+ recorderPromise = Recorder._create(context, params);(context as any)[recorderSymbol] = recorderPromise;}return recorderPromise;}- private static async _create(context: BrowserContext, recorderAppFactory: IRecorderAppFactory, params: channels.BrowserContextEnableRecorderParams = {}): Promise<Recorder> {+ private static async _create(context: BrowserContext, params: channels.BrowserContextEnableRecorderParams = {}): Promise<Recorder> {const recorder = new Recorder(context, params);- const recorderApp = await recorderAppFactory(recorder);- await recorder._install(recorderApp);- recorderApp.start();+ await recorder._install();return recorder;}constructor(context: BrowserContext, params: channels.BrowserContextEnableRecorderParams) {+ super();this._context = context;this._params = params;this._mode = params.mode || 'none';@@ -101,18 +119,18 @@ export class Recorder implements InstrumentationListener, IRecorder {this._signalProcessor = new RecorderSignalProcessor();this._signalProcessor.on('action', (actionInContext: actions.ActionInContext) => {if (this._enabled)- this._recorderApp?.actionAdded(actionInContext);+ this.emit(RecorderEvent.ActionAdded, actionInContext);});this._signalProcessor.on('signal', (signal: Signal) => {if (this._enabled)- this._recorderApp?.signalAdded(signal);+ this.emit(RecorderEvent.SignalAdded, signal);});context.on(BrowserContext.Events.BeforeClose, () => {- this._recorderApp?.flushOutput().catch(() => {});+ this.emit(RecorderEvent.ContextClosed);});this._listeners.push(eventsHelper.addEventListener(process, 'exit', () => {- this._recorderApp?.flushOutput().catch(() => {});+ this.emit(RecorderEvent.ContextClosed);}));this._setEnabled(params.mode === 'recording');@@ -127,57 +145,14 @@ export class Recorder implements InstrumentationListener, IRecorder {}}- private async _install(recorderApp: IRecorderApp) {- this._recorderApp = recorderApp;- recorderApp.once('close', () => {- this._debugger.resume(false);- this._recorderApp = null;- });- recorderApp.on('event', (data: EventData) => {- if (data.event === 'setMode') {- this.setMode(data.params.mode);- return;- }- if (data.event === 'highlightRequested') {- if (data.params.selector)- this.setHighlightedSelector(this._currentLanguage, data.params.selector);- if (data.params.ariaTemplate)- this.setHighlightedAriaTemplate(data.params.ariaTemplate);- return;- }- if (data.event === 'step') {- this._debugger.resume(true);- return;- }- if (data.event === 'languageChanged') {- this._currentLanguage = data.params.language;- this._refreshOverlay();- return;- }- if (data.event === 'resume') {- this._debugger.resume(false);- return;- }- if (data.event === 'pause') {- this._debugger.pauseOnNextStatement();- return;- }- if (data.event === 'clear') {- this._clearScript();- return;- }- });-- await Promise.all([- recorderApp.setMode(this._mode),- recorderApp.setPaused(this._debugger.isPaused()),- this._pushUserSources()- ]);+ private async _install() {+ this.emit(RecorderEvent.ModeChanged, this._mode);+ this.emit(RecorderEvent.PausedStateChanged, this._debugger.isPaused());this._context.once(BrowserContext.Events.Close, () => {eventsHelper.removeEventListeners(this._listeners);this._context.instrumentation.removeListener(this);- this._recorderApp?.close().catch(() => {});+ this.emit(RecorderEvent.ContextClosed);});const controller = new ProgressController(serverSideCallMetadata(), this._context);@@ -210,7 +185,7 @@ export class Recorder implements InstrumentationListener, IRecorder {await this._context.exposeBinding(progress, '__pw_recorderElementPicked', false, async ({ frame }, elementInfo: ElementInfo) => {const selectorChain = await generateFrameSelector(frame);- await this._recorderApp?.elementPicked({ selector: buildFullSelector(selectorChain, elementInfo.selector), ariaSnapshot: elementInfo.ariaSnapshot }, true);+ this.emit(RecorderEvent.ElementPicked, { selector: buildFullSelector(selectorChain, elementInfo.selector), ariaSnapshot: elementInfo.ariaSnapshot }, true);});await this._context.exposeBinding(progress, '__pw_recorderSetMode', false, async ({ frame }, mode: Mode) => {@@ -253,8 +228,6 @@ export class Recorder implements InstrumentationListener, IRecorder {if (this._debugger.isPaused())this._pausedStateChanged();this._debugger.on(Debugger.Events.PausedStateChanged, () => this._pausedStateChanged());-- (this._context as any).recorderAppForTest = this._recorderApp;}private _pausedStateChanged() {@@ -263,17 +236,21 @@ export class Recorder implements InstrumentationListener, IRecorder {if (!this._currentCallsMetadata.has(metadata))this.onBeforeCall(sdkObject, metadata);}- this._recorderApp?.setPaused(this._debugger.isPaused());+ this.emit(RecorderEvent.PausedStateChanged, this._debugger.isPaused());this._updateUserSources();this.updateCallLog([...this._currentCallsMetadata.keys()]);}+ mode() {+ return this._mode;+ }+setMode(mode: Mode) {if (this._mode === mode)return;this._highlightedElement = {};this._mode = mode;- this._recorderApp?.setMode(this._mode);+ this.emit(RecorderEvent.ModeChanged, this._mode);this._setEnabled(this._isRecording());this._debugger.setMuted(this._isRecording());if (this._mode !== 'none' && this._mode !== 'standby' && this._context.pages().length === 1)@@ -281,16 +258,13 @@ export class Recorder implements InstrumentationListener, IRecorder {this._refreshOverlay();}- resume() {- this._debugger.resume(false);- }-- mode() {- return this._mode;+ url(): string | undefined {+ const page = this._context.pages()[0];+ return page?.mainFrame().url();}- setHighlightedSelector(language: Language, selector: string) {- this._highlightedElement = { selector: locatorOrSelectorAsSelector(language, selector, this._context.selectors().testIdAttributeName()) };+ setHighlightedSelector(selector: string) {+ this._highlightedElement = { selector: locatorOrSelectorAsSelector(this._currentLanguage, selector, this._context.selectors().testIdAttributeName()) };this._refreshOverlay();}@@ -299,11 +273,44 @@ export class Recorder implements InstrumentationListener, IRecorder {this._refreshOverlay();}+ step() {+ this._debugger.resume(true);+ }++ setLanguage(language: Language) {+ this._currentLanguage = language;+ this._refreshOverlay();+ }++ resume() {+ this._debugger.resume(false);+ }++ pause() {+ this._debugger.pauseOnNextStatement();+ }++ paused() {+ return this._debugger.isPaused();+ }++ close() {+ this._debugger.resume(false);+ }+hideHighlightedSelector() {this._highlightedElement = {};this._refreshOverlay();}+ userSources() {+ return [...this._userSources.values()];+ }++ callLog(): CallLog[] {+ return this._callLogs;+ }+private async _scopeHighlightedSelectorToFrame(frame: Frame): Promise<string | undefined> {if (!this._highlightedElement.selector)return;@@ -381,11 +388,7 @@ export class Recorder implements InstrumentationListener, IRecorder {source.revealLine = line;}}- this._pushUserSources();- }-- private _pushUserSources() {- this._recorderApp?.userSourcesChanged([...this._userSources.values()]);+ this.emit(RecorderEvent.UserSourcesChanged, this.userSources());}async onBeforeInputAction(sdkObject: SdkObject, metadata: CallMetadata) {@@ -409,7 +412,8 @@ export class Recorder implements InstrumentationListener, IRecorder {status = 'paused';logs.push(metadataToCallLog(metadata, status));}- this._recorderApp?.updateCallLogs(logs);+ this._callLogs = logs;+ this.emit(RecorderEvent.CallLogsUpdated, logs);}private _isRecording() {@@ -431,7 +435,7 @@ export class Recorder implements InstrumentationListener, IRecorder {private async _onPage(page: Page) {// First page is called page, others are called popup1, popup2, etc.const frame = page.mainFrame();- page.on('close', () => {+ page.on(Page.Events.Close, () => {this._signalProcessor.addAction({frame: this._describeMainFrame(page),action: {@@ -472,10 +476,10 @@ export class Recorder implements InstrumentationListener, IRecorder {private _filePrimaryURLChanged() {const page = this._context.pages()[0];- this._recorderApp?.pageNavigated(page?.mainFrame().url());+ this.emit(RecorderEvent.PageNavigated, page?.mainFrame().url());}- private _clearScript(): void {+ clear(): void {if (this._params.mode === 'recording') {for (const page of this._context.pages())this._onFrameNavigated(page.mainFrame(), page);diff --git a/packages/playwright-core/src/server/recorder/recorderApp.ts b/packages/playwright-core/src/server/recorder/recorderApp.tsindex 578da3f7ef..3c89c9bb2d 100644--- a/packages/playwright-core/src/server/recorder/recorderApp.ts+++ b/packages/playwright-core/src/server/recorder/recorderApp.ts@@ -14,7 +14,6 @@* limitations under the License.*/-import { EventEmitter } from 'events';import fs from 'fs';import path from 'path';@@ -28,33 +27,26 @@ import { ThrottledFile } from './throttledFile';import { languageSet } from '../codegen/languages';import { collapseActions } from './recorderUtils';import { generateCode } from '../codegen/language';-import { Recorder } from '../recorder';+import { Recorder, RecorderEvent } from '../recorder';import { monotonicTime } from '../../utils/isomorphic/time';import type { BrowserContext } from '../browserContext';import type { Page } from '../page';-import type { IRecorder, IRecorderApp, IRecorderAppFactory, RecorderAppParams } from './recorderFrontend';import type * as actions from '@recorder/actions';import type { CallLog, ElementInfo, Mode, Source } from '@recorder/recorderTypes';-import type { LanguageGeneratorOptions } from '../codegen/types';+import type { Language, LanguageGeneratorOptions } from '../codegen/types';import type * as channels from '@protocol/channels';-export class EmptyRecorderApp extends EventEmitter implements IRecorderApp {- wsEndpointForTest: undefined;- async close(): Promise<void> {}- async setPaused(paused: boolean): Promise<void> {}- async setMode(mode: Mode): Promise<void> {}- async elementPicked(elementInfo: ElementInfo, userGesture?: boolean): Promise<void> {}- async updateCallLogs(callLogs: CallLog[]): Promise<void> {}- async userSourcesChanged(sources: Source[]): Promise<void> {}- async start() {}- async actionAdded(action: actions.ActionInContext): Promise<void> {}- async signalAdded(signal: actions.Signal): Promise<void> {}- async pageNavigated(url: string): Promise<void> {}- async flushOutput(): Promise<void> {}-}+export type RecorderAppParams = channels.BrowserContextEnableRecorderParams & {+ browserName: string;+ sdkLanguage: Language;+ headed: boolean;+ executablePath?: string;+ channel?: string;+};-export class RecorderApp extends EventEmitter implements IRecorderApp {+export class RecorderApp {+ private _recorder: Recorder;private _page: Page;readonly wsEndpointForTest: string | undefined;private _languageGeneratorOptions: LanguageGeneratorOptions;@@ -64,10 +56,9 @@ export class RecorderApp extends EventEmitter implements IRecorderApp {private _recorderSources: Source[] = [];private _primaryLanguage: string;- constructor(params: RecorderAppParams, page: Page, wsEndpointForTest: string | undefined) {- super();- this.setMaxListeners(0);+ private constructor(recorder: Recorder, params: RecorderAppParams, page: Page, wsEndpointForTest: string | undefined) {this._page = page;+ this._recorder = recorder;this.wsEndpointForTest = wsEndpointForTest;// Make a copy of options to modify them later.@@ -83,7 +74,7 @@ export class RecorderApp extends EventEmitter implements IRecorderApp {this._primaryLanguage = process.env.TEST_INSPECTOR_LANGUAGE || params.language || params.sdkLanguage;}- private async _init() {+ private async _init(inspectedContext: BrowserContext) {await syncLocalStorageWithSettings(this._page, 'recorder');const controller = new ProgressController(serverSideCallMetadata(), this._page);@@ -111,90 +102,90 @@ export class RecorderApp extends EventEmitter implements IRecorderApp {await this._page.exposeBinding(progress, 'dispatch', false, (_, data: any) => this._handleUIEvent(data));this._page.once('close', () => {- this.emit('close');+ this._recorder.close();this._page.browserContext.close({ reason: 'Recorder window closed' }).catch(() => {});+ delete (inspectedContext as any)[recorderAppSymbol];});await this._page.mainFrame().goto(progress, process.env.PW_HMR ? 'http://localhost:44225' : 'https://playwright/index.html');});- }-- start() {- this._updateActions(true);- }-- async actionAdded(action: actions.ActionInContext): Promise<void> {- this._actions.push(action);- this._updateActions();- }- async signalAdded(signal: actions.Signal): Promise<void> {- const lastAction = this._actions[this._actions.length - 1];- if (lastAction)- lastAction.action.signals.push(signal);- this._updateActions();- }+ const url = this._recorder.url();+ if (url)+ this._onPageNavigated(url);+ this._onModeChanged(this._recorder.mode());+ this._onPausedStateChanged(this._recorder.paused());+ this._onUserSourcesChanged(this._recorder.userSources());+ this._onCallLogsUpdated(this._recorder.callLog());+ this._wireListeners(this._recorder);- async pageNavigated(url: string): Promise<void> {- await this._page.mainFrame().evaluateExpression((({ url }: { url: string }) => {- window.playwrightSetPageURL(url);- }).toString(), { isFunction: true }, { url }).catch(() => {});- }-- private _selectedFileChanged(fileId: string) {- const source = [...this._recorderSources, ...this._userSources].find(s => s.id === fileId);- if (source)- this.emit('event', { event: 'languageChanged', params: { language: source.language } });- }-- async close() {- await this._page.browserContext.close({ reason: 'Recorder window closed' });+ this._updateActions(true);}private _handleUIEvent(data: any) {if (data.event === 'clear') {this._actions = [];this._updateActions();- this.emit('clear');+ this._recorder.clear();return;}if (data.event === 'fileChanged') {- this._selectedFileChanged(data.params.fileId);+ const source = [...this._recorderSources, ...this._userSources].find(s => s.id === data.params.fileId);+ if (source)+ this._recorder.setLanguage(source.language);return;}-- // Pass through events.- this.emit('event', data);+ if (data.event === 'setMode') {+ this._recorder.setMode(data.params.mode);+ return;+ }+ if (data.event === 'resume') {+ this._recorder.resume();+ return;+ }+ if (data.event === 'pause') {+ this._recorder.pause();+ return;+ }+ if (data.event === 'step') {+ this._recorder.step();+ return;+ }+ if (data.event === 'highlightRequested') {+ if (data.params.selector)+ this._recorder.setHighlightedSelector(data.params.selector);+ if (data.params.ariaTemplate)+ this._recorder.setHighlightedAriaTemplate(data.params.ariaTemplate);+ return;+ }+ throw new Error(`Unknown event: ${data.event}`);}static async show(context: BrowserContext, params: channels.BrowserContextEnableRecorderParams) {- const factory = RecorderApp._factory(context, params);- await Recorder.show(context, factory, params);+ if (process.env.PW_CODEGEN_NO_INSPECTOR)+ return;+ const recorder = await Recorder.forContext(context, params);+ await RecorderApp._show(recorder, context, params);}- static showInspectorNoReply(context: BrowserContext) {- Recorder.showInspector(context, {}, RecorderApp._factory(context, {})).catch(() => {});+ async close() {+ await this._page.close();}- private static _factory(context: BrowserContext, params: channels.BrowserContextEnableRecorderParams): IRecorderAppFactory {- const appParams = {- browserName: context._browser.options.name,- sdkLanguage: context._browser.sdkLanguage(),- wsEndpointForTest: context._browser.options.wsEndpoint,- ...params,- };- return async recorder => {- if (process.env.PW_CODEGEN_NO_INSPECTOR)- return new EmptyRecorderApp();- return await RecorderApp._open(appParams, recorder, context);- };+ static showInspectorNoReply(context: BrowserContext) {+ if (process.env.PW_CODEGEN_NO_INSPECTOR)+ return;+ void Recorder.forContext(context, {}).then(recorder => RecorderApp._show(recorder, context, {})).catch(() => {});}- private static async _open(params: RecorderAppParams, recorder: IRecorder, inspectedContext: BrowserContext): Promise<IRecorderApp> {+ private static async _show(recorder: Recorder, inspectedContext: BrowserContext, params: channels.BrowserContextEnableRecorderParams) {+ if ((inspectedContext as any)[recorderAppSymbol])+ return;+ (inspectedContext as any)[recorderAppSymbol] = true;const sdkLanguage = inspectedContext._browser.sdkLanguage();const headed = !!inspectedContext._browser.options.headful;const recorderPlaywright = (require('../playwright').createPlaywright as typeof import('../playwright').createPlaywright)({ sdkLanguage: 'javascript', isInternalPlaywright: true });- const { context, page } = await launchApp(recorderPlaywright.chromium, {+ const { context: appContext, page } = await launchApp(recorderPlaywright.chromium, {sdkLanguage,windowSize: { width: 600, height: 600 },windowPosition: { x: 1020, y: 10 },@@ -208,35 +199,120 @@ export class RecorderApp extends EventEmitter implements IRecorderApp {channel: inspectedContext._browser.options.isChromium ? inspectedContext._browser.options.channel : undefined,}});- const controller = new ProgressController(serverSideCallMetadata(), context._browser);+ const controller = new ProgressController(serverSideCallMetadata(), appContext._browser);await controller.run(async progress => {- await context._browser._defaultContext!._loadDefaultContextAsIs(progress);+ await appContext._browser._defaultContext!._loadDefaultContextAsIs(progress);});- const result = new RecorderApp(params, page, context._browser.options.wsEndpoint);- await result._init();- return result;+ const appParams = {+ browserName: inspectedContext._browser.options.name,+ sdkLanguage: inspectedContext._browser.sdkLanguage(),+ wsEndpointForTest: inspectedContext._browser.options.wsEndpoint,+ headed: !!inspectedContext._browser.options.headful,+ executablePath: inspectedContext._browser.options.isChromium ? inspectedContext._browser.options.customExecutablePath : undefined,+ channel: inspectedContext._browser.options.isChromium ? inspectedContext._browser.options.channel : undefined,+ ...params,+ };++ const recorderApp = new RecorderApp(recorder, appParams, page, appContext._browser.options.wsEndpoint);+ await recorderApp._init(inspectedContext);+ (inspectedContext as any).recorderAppForTest = recorderApp;}- async setMode(mode: Mode): Promise<void> {- await this._page.mainFrame().evaluateExpression(((mode: Mode) => {+ private _wireListeners(recorder: Recorder) {+ recorder.on(RecorderEvent.ActionAdded, (action: actions.ActionInContext) => {+ this._onActionAdded(action);+ });++ recorder.on(RecorderEvent.SignalAdded, (signal: actions.Signal) => {+ this._onSignalAdded(signal);+ });++ recorder.on(RecorderEvent.PageNavigated, (url: string) => {+ this._onPageNavigated(url);+ });++ recorder.on(RecorderEvent.ContextClosed, () => {+ this._onContextClosed();+ });++ recorder.on(RecorderEvent.ModeChanged, (mode: Mode) => {+ this._onModeChanged(mode);+ });++ recorder.on(RecorderEvent.PausedStateChanged, (paused: boolean) => {+ this._onPausedStateChanged(paused);+ });++ recorder.on(RecorderEvent.UserSourcesChanged, (sources: Source[]) => {+ this._onUserSourcesChanged(sources);+ });++ recorder.on(RecorderEvent.ElementPicked, (elementInfo: ElementInfo, userGesture?: boolean) => {+ this._onElementPicked(elementInfo, userGesture);+ });++ recorder.on(RecorderEvent.CallLogsUpdated, (callLogs: CallLog[]) => {+ this._onCallLogsUpdated(callLogs);+ });+ }++ private _onActionAdded(action: actions.ActionInContext) {+ this._actions.push(action);+ this._updateActions();+ }++ private _onSignalAdded(signal: actions.Signal) {+ const lastAction = this._actions[this._actions.length - 1];+ if (lastAction)+ lastAction.action.signals.push(signal);+ this._updateActions();+ }++ private _onPageNavigated(url: string) {+ this._page.mainFrame().evaluateExpression((({ url }: { url: string }) => {+ window.playwrightSetPageURL(url);+ }).toString(), { isFunction: true }, { url }).catch(() => {});+ }++ private _onContextClosed() {+ this._throttledOutputFile?.flush();+ this._page.browserContext.close({ reason: 'Recorder window closed' }).catch(() => {});+ }++ private _onModeChanged(mode: Mode) {+ this._page.mainFrame().evaluateExpression(((mode: Mode) => {window.playwrightSetMode(mode);}).toString(), { isFunction: true }, mode).catch(() => {});}- async setPaused(paused: boolean): Promise<void> {- await this._page.mainFrame().evaluateExpression(((paused: boolean) => {+ private _onPausedStateChanged(paused: boolean) {+ this._page.mainFrame().evaluateExpression(((paused: boolean) => {window.playwrightSetPaused(paused);}).toString(), { isFunction: true }, paused).catch(() => {});}- async userSourcesChanged(sources: Source[]): Promise<void> {+ private _onUserSourcesChanged(sources: Source[]) {if (!sources.length && !this._userSources.length)return;this._userSources = sources;this._pushAllSources();}+ private _onElementPicked(elementInfo: ElementInfo, userGesture?: boolean) {+ if (userGesture)+ this._page.bringToFront();+ this._page.mainFrame().evaluateExpression(((param: { elementInfo: ElementInfo, userGesture?: boolean }) => {+ window.playwrightElementPicked(param.elementInfo, param.userGesture);+ }).toString(), { isFunction: true }, { elementInfo, userGesture }).catch(() => {});+ }++ private _onCallLogsUpdated(callLogs: CallLog[]) {+ this._page.mainFrame().evaluateExpression(((callLogs: CallLog[]) => {+ window.playwrightUpdateLogs(callLogs);+ }).toString(), { isFunction: true }, callLogs).catch(() => {});+ }+private async _pushAllSources() {const sources = [...this._userSources, ...this._recorderSources];this._page.mainFrame().evaluateExpression((({ sources }: { sources: Source[] }) => {@@ -247,28 +323,10 @@ export class RecorderApp extends EventEmitter implements IRecorderApp {if (process.env.PWTEST_CLI_IS_UNDER_TEST && sources.length) {const primarySource = sources.find(s => s.isPrimary);if ((process as any)._didSetSourcesForTest(primarySource?.text ?? ''))- this.close();+ this._page.close().catch(() => {});}}- async elementPicked(elementInfo: ElementInfo, userGesture?: boolean): Promise<void> {- if (userGesture)- this._page.bringToFront();- await this._page.mainFrame().evaluateExpression(((param: { elementInfo: ElementInfo, userGesture?: boolean }) => {- window.playwrightElementPicked(param.elementInfo, param.userGesture);- }).toString(), { isFunction: true }, { elementInfo, userGesture }).catch(() => {});- }-- async updateCallLogs(callLogs: CallLog[]): Promise<void> {- await this._page.mainFrame().evaluateExpression(((callLogs: CallLog[]) => {- window.playwrightUpdateLogs(callLogs);- }).toString(), { isFunction: true }, callLogs).catch(() => {});- }-- async flushOutput(): Promise<void> {- this._throttledOutputFile?.flush();- }-private _updateActions(initial: boolean = false) {const timestamp = initial ? 0 : monotonicTime();const recorderSources = [];@@ -300,3 +358,5 @@ export class RecorderApp extends EventEmitter implements IRecorderApp {this._pushAllSources();}}++const recorderAppSymbol = Symbol('recorderApp');diff --git a/packages/playwright-core/src/server/recorder/recorderFrontend.ts b/packages/playwright-core/src/server/recorder/recorderFrontend.tsdeleted file mode 100644index dca4148611..0000000000--- a/packages/playwright-core/src/server/recorder/recorderFrontend.ts+++ /dev/null@@ -1,48 +0,0 @@-/**- * Copyright (c) Microsoft Corporation.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import type * as actions from '@recorder/actions';-import type { CallLog, ElementInfo, Mode, Source } from '@recorder/recorderTypes';-import type { EventEmitter } from 'events';-import type * as channels from '@protocol/channels';-import type { Language } from '../codegen/types';--export interface IRecorder {- setMode(mode: Mode): void;- mode(): Mode;-}--export interface IRecorderApp extends EventEmitter {- readonly wsEndpointForTest: string | undefined;- close(): Promise<void>;- setPaused(paused: boolean): Promise<void>;- setMode(mode: Mode): Promise<void>;- elementPicked(elementInfo: ElementInfo, userGesture?: boolean): Promise<void>;- updateCallLogs(callLogs: CallLog[]): Promise<void>;- userSourcesChanged(sources: Source[]): Promise<void>;- start(): void;- actionAdded(action: actions.ActionInContext): Promise<void>;- signalAdded(signal: actions.Signal): Promise<void>;- pageNavigated(url: string): Promise<void>;- flushOutput(): Promise<void>;-}--export type RecorderAppParams = channels.BrowserContextEnableRecorderParams & {- browserName: string;- sdkLanguage: Language;-};--export type IRecorderAppFactory = (recorder: IRecorder) => Promise<IRecorderApp>;diff --git a/packages/playwright-core/src/server/webkit/wkBrowser.ts b/packages/playwright-core/src/server/webkit/wkBrowser.tsindex f1eccfd100..0a34cb1129 100644--- a/packages/playwright-core/src/server/webkit/wkBrowser.ts+++ b/packages/playwright-core/src/server/webkit/wkBrowser.ts@@ -175,8 +175,8 @@ export class WKBrowser extends Browser {const wkPage = this._wkPages.get(pageProxyId);if (!wkPage)return;- wkPage.didClose();this._wkPages.delete(pageProxyId);+ wkPage.didClose();}_onPageProxyMessageReceived(event: PageProxyMessageReceivedPayload) {diff --git a/tests/library/inspector/title.spec.ts b/tests/library/inspector/title.spec.tsindex 17dd0e3fb2..b4dd50ee36 100644--- a/tests/library/inspector/title.spec.ts+++ b/tests/library/inspector/title.spec.ts@@ -47,35 +47,13 @@ test('should update primary page URL when original primary closes', async ({);const page2 = await context.newPage();- await page2.goto(`${server.PREFIX}/empty.html`);+ await page2.goto(`${server.PREFIX}/dom.html`);await expect(recorder.recorderPage).toHaveTitle(`Playwright Inspector - ${server.PREFIX}/background-color.html`,);- const page3 = await context.newPage();- await page3.goto(`${server.PREFIX}/dom.html`);- await expect(recorder.recorderPage).toHaveTitle(- `Playwright Inspector - ${server.PREFIX}/background-color.html`,- );-- const page4 = await context.newPage();- await page4.goto(`${server.PREFIX}/grid.html`);- await expect(recorder.recorderPage).toHaveTitle(- `Playwright Inspector - ${server.PREFIX}/background-color.html`,- );-- await page2.close();- await expect(recorder.recorderPage).toHaveTitle(- `Playwright Inspector - ${server.PREFIX}/background-color.html`,- );-- await recorder.page.close();+ await context.pages()[0].close();await expect(recorder.recorderPage).toHaveTitle(`Playwright Inspector - ${server.PREFIX}/dom.html`,);-- await page3.close();- await expect(recorder.recorderPage).toHaveTitle(- `Playwright Inspector - ${server.PREFIX}/grid.html`,- );});