| // Copyright 2026 The Chromium Authors | |
| // Use of this source code is governed by a BSD-style license that can be | |
| // found in the LICENSE file. | |
| import type * as puppeteer from 'puppeteer-core'; | |
| import type * as ProtocolClient from '../../front_end/core/protocol_client/protocol_client.js'; | |
| import {PuppeteerDevToolsConnection} from '../../front_end/core/protocol_client/PuppeteerDevToolsConnection.js'; | |
| import type * as SDK from '../../front_end/core/sdk/sdk.js'; | |
| import type * as Foundation from '../../front_end/foundation/foundation.js'; | |
| const STARTUP_CDP_TIMEOUT_MS = 10_000; | |
| class StartupTrackingCDPConnection extends PuppeteerDevToolsConnection { | |
| #tracking = true; | |
| readonly #pending = new Map<Promise<unknown>, string>(); | |
| override send<T extends ProtocolClient.CDPConnection.Command>( | |
| method: T, | |
| params: ProtocolClient.CDPConnection.CommandParams<T>, | |
| sessionId: string|undefined, | |
| ): | |
| Promise<|{result: ProtocolClient.CDPConnection.CommandResult<T>}|{error: ProtocolClient.CDPConnection.CDPError}> { | |
| const promise = super.send(method, params, sessionId); | |
| if (this.#tracking) { | |
| this.#pending.set(promise, method); | |
| const onSettled = (): void => { | |
| this.#pending.delete(promise); | |
| }; | |
| void promise.then(onSettled, onSettled); | |
| } | |
| return promise; | |
| } | |
| async waitForPendingCommands(timeoutMs: number): Promise<void> { | |
| let timeoutId: ReturnType<typeof setTimeout>|undefined; | |
| try { | |
| const drain = async(): Promise<void> => { | |
| while (this.#tracking) { | |
| if (this.#pending.size > 0) { | |
| await Promise.allSettled([...this.#pending.keys()]); | |
| } | |
| // Yield a macrotask so continuations chained onto initial CDP | |
| // responses (e.g. OverlayModel.#wireAgentToSettings) can dispatch | |
| // follow-up startup commands before we declare startup quiescent. | |
| await new Promise<void>(resolve => setImmediate(resolve)); | |
| if (this.#pending.size === 0) { | |
| break; | |
| } | |
| } | |
| }; | |
| const timeout = new Promise<never>((_, reject) => { | |
| timeoutId = setTimeout(() => { | |
| const pendingMethods = [...this.#pending.values()].join(', ') || '<none>'; | |
| reject(new Error( | |
| `Timed out after ${timeoutMs}ms waiting for initial CDP commands to settle: ${pendingMethods}`, | |
| )); | |
| }, timeoutMs); | |
| }); | |
| await Promise.race([drain(), timeout]); | |
| } finally { | |
| if (timeoutId !== undefined) { | |
| clearTimeout(timeoutId); | |
| } | |
| this.#tracking = false; | |
| this.#pending.clear(); | |
| } | |
| } | |
| } | |
| export interface TargetUniverse { | |
| /** The DevTools target corresponding to the puppeteer Page */ | |
| target: SDK.Target.Target; | |
| universe: Foundation.Universe.Universe; | |
| /** The secondary session created for this page */ | |
| session: puppeteer.CDPSession; | |
| cleanup: () => void; | |
| } | |
| let registeredExtensions = false; | |
| export async function createTargetUniverse( | |
| session: puppeteer.CDPSession, | |
| options?: Partial<Foundation.Universe.CreationOptions>, | |
| ): Promise<TargetUniverse> { | |
| // DevTools modules contain top-level await in their ES module graphs. | |
| // Because Node executes test scripts as CommonJS, top-level static imports | |
| // of these modules fail at startup with ERR_REQUIRE_ASYNC_MODULE. | |
| // We use dynamic `import()` at runtime to load the ESM graph asynchronously. | |
| const [Common, Host, SDKModule, RootModule, Foundation, Formatter] = await Promise.all([ | |
| import('../../front_end/core/common/common.js'), | |
| import('../../front_end/core/host/host.js'), | |
| import('../../front_end/core/sdk/sdk.js'), | |
| import('../../front_end/core/root/root.js'), | |
| import('../../front_end/foundation/foundation.js'), | |
| import('../../front_end/models/formatter/formatter.js'), | |
| ]); | |
| if (!registeredExtensions) { | |
| registeredExtensions = true; | |
| // Register experiments expected by models | |
| RootModule.Runtime.experiments.register({ | |
| name: RootModule.ExperimentNames.ExperimentName.INSTRUMENTATION_BREAKPOINTS, | |
| title: 'Instrumentation breakpoints', | |
| aboutFlag: 'devtools-instrumentation-breakpoints', | |
| isEnabled: RootModule.Runtime.hostConfig.devToolsInstrumentationBreakpoints?.enabled ?? false, | |
| requiresChromeRestart: false, | |
| }); | |
| } | |
| const originalHostConfig = {...RootModule.Runtime.hostConfig}; | |
| const originalInspectorFrontendHost = Host.InspectorFrontendHost.InspectorFrontendHostInstance; | |
| const originalInspectorFrontendHostEvents = originalInspectorFrontendHost.events; | |
| const globalContext = RootModule.DevToolsContext.globalInstance(); | |
| const originalSettings = | |
| globalContext.has(Common.Settings.Settings) ? globalContext.get(Common.Settings.Settings) : undefined; | |
| let cleanedUp = false; | |
| let universe: Foundation.Universe.Universe|undefined; | |
| let connection: StartupTrackingCDPConnection|undefined; | |
| const cleanup = (): void => { | |
| if (cleanedUp) { | |
| return; | |
| } | |
| cleanedUp = true; | |
| const errors: unknown[] = []; | |
| const runCleanupStep = (step: () => void): void => { | |
| try { | |
| step(); | |
| } catch (err) { | |
| errors.push(err); | |
| } | |
| }; | |
| runCleanupStep(() => universe?.dispose()); | |
| runCleanupStep(() => connection?.dispose('Target universe cleanup')); | |
| runCleanupStep(() => Formatter.FormatterWorkerPool.FormatterWorkerPool.removeInstance()); | |
| runCleanupStep(() => { | |
| for (const key of Object.keys(RootModule.Runtime.hostConfig)) { | |
| delete (RootModule.Runtime.hostConfig as Record<string, unknown>)[key]; | |
| } | |
| Object.assign(RootModule.Runtime.hostConfig, originalHostConfig); | |
| Host.InspectorFrontendHost.installInspectorFrontendHost(originalInspectorFrontendHost); | |
| originalInspectorFrontendHost.events = originalInspectorFrontendHostEvents; | |
| if (originalSettings) { | |
| globalContext.set(Common.Settings.Settings, originalSettings); | |
| } else { | |
| Common.Settings.Settings.removeInstance(); | |
| } | |
| }); | |
| if (errors.length === 1) { | |
| throw errors[0]; | |
| } | |
| if (errors.length > 1) { | |
| throw new AggregateError(errors, 'Multiple errors during target universe cleanup'); | |
| } | |
| }; | |
| try { | |
| for (const key of Object.keys(RootModule.Runtime.hostConfig)) { | |
| delete (RootModule.Runtime.hostConfig as Record<string, unknown>)[key]; | |
| } | |
| if (options?.hostConfig) { | |
| Object.assign(RootModule.Runtime.hostConfig, options.hostConfig); | |
| } | |
| const hostInstance = options?.inspectorFrontendHost ?? Host.InspectorFrontendHost.InspectorFrontendHostInstance; | |
| Host.InspectorFrontendHost.installInspectorFrontendHost(hostInstance); | |
| const settingStorage = new Common.Settings.SettingsStorage({}); | |
| universe = new Foundation.Universe.Universe({ | |
| settingsCreationOptions: { | |
| syncedStorage: settingStorage, | |
| globalStorage: settingStorage, | |
| localStorage: settingStorage, | |
| ...options?.settingsCreationOptions, | |
| }, | |
| hostConfig: options?.hostConfig ?? {}, | |
| inspectorFrontendHost: hostInstance, | |
| supportsEmulation: options?.supportsEmulation ?? false, | |
| overrideAutoStartModels: options?.overrideAutoStartModels, | |
| }); | |
| connection = new StartupTrackingCDPConnection( | |
| session as unknown as ConstructorParameters<typeof PuppeteerDevToolsConnection>[0], | |
| ); | |
| const targetManager = universe.context.get(SDKModule.TargetManager.TargetManager); | |
| const target = targetManager.createTarget( | |
| 'main', | |
| '', | |
| SDKModule.Target.Type.FRAME, | |
| /* parentTarget */ null, | |
| session.id(), | |
| undefined, | |
| connection, | |
| ); | |
| await connection.waitForPendingCommands(STARTUP_CDP_TIMEOUT_MS); | |
| return {target, universe, session, cleanup}; | |
| } catch (err) { | |
| try { | |
| cleanup(); | |
| } catch (cleanupErr) { | |
| console.error('Unexpected error during target universe cleanup after setup failure', cleanupErr); | |
| } | |
| throw err; | |
| } | |
| } |