| /** | |
| * @license | |
| * Copyright 2026 Google LLC | |
| * SPDX-License-Identifier: Apache-2.0 | |
| */ | |
| import {Script} from 'node:vm'; | |
| import { | |
| type TargetUniverse, | |
| waitForSourceMaps, | |
| } from './devtools/DevtoolsUtils.js'; | |
| import {DevTools} from './third_party/browser.js'; | |
| import { | |
| type GeneratedLocation, | |
| type Logpoint, | |
| LogpointError, | |
| type LogpointOptions, | |
| } from './utils/logpoint.js'; | |
| type Universe = DevTools.Foundation.Universe.Universe; | |
| type Breakpoint = DevTools.BreakpointManager.Breakpoint; | |
| type UserCondition = DevTools.BreakpointManager.UserCondition; | |
| type UISourceCode = DevTools.Workspace.UISourceCode.UISourceCode; | |
| interface ResolvedLogpoint { | |
| options: LogpointOptions; | |
| uiSourceCode: UISourceCode; | |
| key: string; | |
| } | |
| /** | |
| * Checks that the expression parses as `console.log()` arguments. V8 is used | |
| * for parsing both here and in the browser, so an expression that is rejected | |
| * here would also be rejected as a breakpoint condition. The script is only | |
| * compiled, never run. | |
| */ | |
| export function validateExpression(expression: string): void { | |
| try { | |
| new Script(`console.log(${expression})`); | |
| } catch (error) { | |
| throw new Error( | |
| `The logpoint expression \`${expression}\` does not compile: ${error instanceof Error ? error.message : String(error)}. Provide the expression like arguments to console.log(...).`, | |
| ); | |
| } | |
| } | |
| /** | |
| * DevTools brands breakpoint conditions nominally; any string is a valid | |
| * user condition. | |
| */ | |
| function toUserCondition(expression: string): UserCondition; | |
| function toUserCondition(expression: string): string { | |
| return expression; | |
| } | |
| function isFromSourceMap(uiSourceCode: UISourceCode): boolean { | |
| return uiSourceCode.contentType().isFromSourceMap(); | |
| } | |
| function locationKey( | |
| url: string, | |
| lineNumber: number, | |
| columnNumber: number | undefined, | |
| ): string { | |
| return `${url}:${lineNumber}${columnNumber === undefined ? '' : `:${columnNumber}`}`; | |
| } | |
| function baseName(url: string): string { | |
| return url.slice(url.lastIndexOf('/') + 1).toLowerCase(); | |
| } | |
| /** | |
| * How long to wait for the source maps of the page to load before an original | |
| * source URL is reported as unknown. Loads still pending then continue in the | |
| * background, so a retry finds the source. | |
| */ | |
| const SOURCE_MAP_LOAD_TIMEOUT_MS = 5_000; | |
| /** | |
| * Manages logpoints for a single page on top of the `BreakpointManager` of | |
| * the page's DevTools universe. | |
| * | |
| * A logpoint is a DevTools breakpoint with `isLogpoint` set: its condition | |
| * logs the expression and never pauses. The breakpoint manager resolves the | |
| * location through source maps, substitutes minified variable names in the | |
| * expression and keeps the breakpoint bound across reloads and rebuilt | |
| * bundles. This class only maps the tool API (URLs and 1-based positions) | |
| * onto workspace source codes. | |
| */ | |
| export class LogpointManager { | |
| readonly #universe: Universe; | |
| readonly #target: DevTools.Target; | |
| /** | |
| * The breakpoints that are logpoints of this page. The breakpoint manager | |
| * keeps one `Breakpoint` per normalized location, so two requested | |
| * locations can share one entry. | |
| */ | |
| readonly #records = new Set<Breakpoint>(); | |
| constructor(devTools: TargetUniverse) { | |
| this.#universe = devTools.universe; | |
| this.#target = devTools.target; | |
| } | |
| get #debuggerModel(): DevTools.DebuggerModel { | |
| const model = this.#target.model(DevTools.DebuggerModel); | |
| if (!model) { | |
| throw new Error('The DevTools debugger model is not available.'); | |
| } | |
| return model; | |
| } | |
| /** | |
| * Makes the given logpoints the complete set of logpoints on the page: | |
| * logpoints not in the list are removed, new ones are added and the | |
| * expression of an existing logpoint at the same location is replaced. | |
| * Expressions and locations are validated before anything is changed. | |
| * Throws a {@link LogpointError} when a location has no executable code; | |
| * the other logpoints are applied regardless. | |
| */ | |
| async setLogpoints(desired: LogpointOptions[]): Promise<Logpoint[]> { | |
| for (const options of desired) { | |
| validateExpression(options.expression); | |
| } | |
| const resolved = new Map<string, ResolvedLogpoint>(); | |
| for (const options of desired) { | |
| const uiSourceCode = await this.#findUISourceCode(options.url); | |
| const key = locationKey( | |
| uiSourceCode.url(), | |
| options.lineNumber, | |
| options.columnNumber, | |
| ); | |
| // The last entry for a location wins, like setting it twice would. | |
| resolved.set(key, {options, uiSourceCode, key}); | |
| } | |
| const kept = new Set<Breakpoint>(); | |
| const unbound: string[] = []; | |
| for (const {options, uiSourceCode, key} of resolved.values()) { | |
| const breakpoint = await this.#universe.breakpointManager.setBreakpoint( | |
| uiSourceCode, | |
| // The tool API is 1-based like the DevTools UI; the model is 0-based. | |
| options.lineNumber - 1, | |
| options.columnNumber === undefined | |
| ? undefined | |
| : options.columnNumber - 1, | |
| toUserCondition(options.expression), | |
| /* enabled */ true, | |
| /* isLogpoint */ true, | |
| DevTools.BreakpointManager.BreakpointOrigin.USER_ACTION, | |
| ); | |
| if (!breakpoint) { | |
| unbound.push(key); | |
| continue; | |
| } | |
| // Wait for the breakpoint to be set in the backend so that the result | |
| // reports whether the location resolved. | |
| await breakpoint.updateBreakpoint(); | |
| if (!this.#records.has(breakpoint) && !breakpoint.bound()) { | |
| await breakpoint.remove(/* keepInStorage */ false); | |
| unbound.push(key); | |
| continue; | |
| } | |
| this.#records.add(breakpoint); | |
| kept.add(breakpoint); | |
| } | |
| for (const breakpoint of [...this.#records]) { | |
| if (!kept.has(breakpoint)) { | |
| this.#records.delete(breakpoint); | |
| await breakpoint.remove(/* keepInStorage */ false); | |
| } | |
| } | |
| this.#setLazySourceMapLoading(this.#records.size === 0); | |
| const logpoints = this.#currentLogpoints(); | |
| if (unbound.length) { | |
| throw new LogpointError( | |
| `No executable code at ${unbound.join(', ')} (for example a comment, type annotation or empty line, or a line not mapped to the generated script). Pick lines containing executable code. The other logpoints were applied.`, | |
| logpoints, | |
| ); | |
| } | |
| return logpoints; | |
| } | |
| /** | |
| * Releases the records. The breakpoints are not removed from the backend: | |
| * the universe is being disposed and its session detaches, which removes | |
| * them along with the page. | |
| */ | |
| dispose(): void { | |
| this.#records.clear(); | |
| } | |
| #currentLogpoints(): Logpoint[] { | |
| return [...this.#records].map(breakpoint => this.#snapshot(breakpoint)); | |
| } | |
| /** | |
| * Reads the current state of a breakpoint, so that the result reflects | |
| * the normalized location and the re-binding done by the breakpoint | |
| * manager after reloads. The breakpoint manager may have moved a | |
| * generated location to its original source, so whether the logpoint is | |
| * source-mapped follows from the breakpoint, not from the request. | |
| */ | |
| #snapshot(breakpoint: Breakpoint): Logpoint { | |
| const sourceMapped = [...breakpoint.getUiSourceCodes()].some( | |
| isFromSourceMap, | |
| ); | |
| const modelBreakpoint = breakpoint.modelBreakpoint(this.#debuggerModel); | |
| const generatedLocations: GeneratedLocation[] = []; | |
| if (breakpoint.bound()) { | |
| for (const position of modelBreakpoint?.currentState ?? []) { | |
| generatedLocations.push({ | |
| url: position.url, | |
| lineNumber: position.lineNumber + 1, | |
| columnNumber: (position.columnNumber ?? 0) + 1, | |
| }); | |
| } | |
| } | |
| const columnNumber = breakpoint.columnNumber(); | |
| return { | |
| url: breakpoint.url(), | |
| lineNumber: breakpoint.lineNumber() + 1, | |
| columnNumber: columnNumber === undefined ? undefined : columnNumber + 1, | |
| expression: breakpoint.condition(), | |
| sourceMapped, | |
| generatedLocations, | |
| }; | |
| } | |
| /** | |
| * Source maps load lazily by default, so after a reload the original | |
| * sources of a rebuilt bundle would not re-appear in the workspace and a | |
| * logpoint on an original source file could not be re-bound to the new | |
| * generated location. While logpoints exist, source maps are loaded | |
| * eagerly instead, like DevTools does with the Sources panel open. | |
| */ | |
| #setLazySourceMapLoading(lazy: boolean): void { | |
| this.#universe.settings | |
| .resolve(DevTools.SourceMapManager.lazyLoadingSettingDescriptor) | |
| .set(lazy); | |
| } | |
| /** | |
| * Finds the workspace source code for a script or original source URL, | |
| * loading source maps if needed. Throws a descriptive error, including | |
| * sources with the same file name, when nothing matches. | |
| */ | |
| async #findUISourceCode(url: string): Promise<UISourceCode> { | |
| // Source maps are loaded lazily in the DevTools universe and original | |
| // sources only appear in the workspace once their source map has loaded. | |
| let match = this.#matchUISourceCode(url); | |
| if (!match) { | |
| // The page may have parsed the script already without the debugger | |
| // model knowing it yet, for example right after a navigation. | |
| await this.#flushDebuggerEvents(); | |
| match = this.#matchUISourceCode(url); | |
| } | |
| let timedOut = false; | |
| if (match && !isFromSourceMap(match)) { | |
| // The script may be a transpiled file served at the URL of its original | |
| // source (see #matchUISourceCode); its source map decides. | |
| const matchedUrl = match.url(); | |
| const scripts = this.#debuggerModel | |
| .scripts() | |
| .filter(script => script.sourceURL === matchedUrl); | |
| if (scripts.some(script => script.sourceMapURL)) { | |
| const signal = AbortSignal.timeout(SOURCE_MAP_LOAD_TIMEOUT_MS); | |
| await waitForSourceMaps(this.#debuggerModel, scripts, signal); | |
| match = this.#matchUISourceCode(url); | |
| if (signal.aborted && (!match || !isFromSourceMap(match))) { | |
| // Setting the logpoint on the served script would use its line | |
| // numbers instead of those of the original source. | |
| throw new Error( | |
| `The source map of ${matchedUrl} was still loading after ${SOURCE_MAP_LOAD_TIMEOUT_MS / 1000} seconds; retry.`, | |
| ); | |
| } | |
| } | |
| } else if (!match) { | |
| const signal = AbortSignal.timeout(SOURCE_MAP_LOAD_TIMEOUT_MS); | |
| await waitForSourceMaps( | |
| this.#debuggerModel, | |
| this.#debuggerModel.scripts(), | |
| signal, | |
| ); | |
| timedOut = signal.aborted; | |
| match = this.#matchUISourceCode(url); | |
| } | |
| if (match) { | |
| return match; | |
| } | |
| const name = baseName(url); | |
| const similar = [...this.#pageSourceCodes()] | |
| .map(uiSourceCode => uiSourceCode.url()) | |
| .filter(candidate => baseName(candidate) === name) | |
| .slice(0, 5); | |
| throw new Error( | |
| `No parsed script or original source file matches "${url}". The url must match the URL of a script as served to the browser or an original source file from a source map, exactly or as a path suffix.${timedOut ? ` Some source maps were still loading after ${SOURCE_MAP_LOAD_TIMEOUT_MS / 1000} seconds; retry if the file comes from a source map.` : ''}${similar.length ? ` Sources with the same file name: ${similar.join(', ')}.` : ''}`, | |
| ); | |
| } | |
| /** | |
| * Waits until the debugger model has received the scripts the page has | |
| * parsed so far. A navigation is awaited on the session of the page, while | |
| * `Debugger.scriptParsed` events arrive on the session of the DevTools | |
| * universe, so they can still be in flight when the navigation is done. | |
| * Events and responses of one session are ordered: once the response to a | |
| * command arrives, the events sent before it have been handled. | |
| */ | |
| async #flushDebuggerEvents(): Promise<void> { | |
| await this.#target.runtimeAgent().invoke_getHeapUsage(); | |
| } | |
| /** The scripts and source-map sources of the page in the workspace. */ | |
| *#pageSourceCodes(): Iterable<UISourceCode> { | |
| for (const uiSourceCode of this.#universe.workspace.uiSourceCodes()) { | |
| const projectType = uiSourceCode.project().type(); | |
| // Content scripts of extensions are left out: they are not part of the | |
| // page under development and would make path-suffix matches ambiguous. | |
| if (projectType === DevTools.Workspace.Workspace.projectTypes.Network) { | |
| yield uiSourceCode; | |
| } | |
| } | |
| } | |
| /** | |
| * Finds the workspace source code for a script or original source URL. | |
| * An exact URL match wins; otherwise the URL is matched as a path suffix so | |
| * that users can pass "src/app.ts" without knowing the bundler's URL | |
| * scheme. An ambiguous suffix match is reported as an error. | |
| */ | |
| #matchUISourceCode(url: string): UISourceCode | null { | |
| const candidates = new Map<string, UISourceCode>(); | |
| for (const uiSourceCode of this.#pageSourceCodes()) { | |
| const candidateUrl = uiSourceCode.url(); | |
| if (candidateUrl !== url && !candidateUrl.endsWith('/' + url)) { | |
| continue; | |
| } | |
| // Dev servers like Vite serve a transpiled file at the URL of its | |
| // original source, with a source map pointing back at that same URL. | |
| // The original source then has the line numbers of the file on disk, | |
| // so it wins over the script served at the same URL. | |
| const existing = candidates.get(candidateUrl); | |
| if (!existing || isFromSourceMap(uiSourceCode)) { | |
| candidates.set(candidateUrl, uiSourceCode); | |
| } | |
| } | |
| const exact = candidates.get(url); | |
| if (exact) { | |
| return exact; | |
| } | |
| if (candidates.size > 1) { | |
| throw new Error( | |
| `"${url}" matches multiple sources: ${[...candidates.keys()].join(', ')}. Specify a longer path.`, | |
| ); | |
| } | |
| return candidates.values().next().value ?? null; | |
| } | |
| } |