Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions docs/SPEC.md

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion src/main/inspector/adapter/adapterSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,14 @@ export const ADAPTER_SOURCE = `function (mode, arg, edit, registry) {
${ANGULAR_JS}
${ELEMENT_JS}
${TREE_JS}
// Each function once (a level of 500 rows of one component names it 500 times): main places each with a call.
const fns = [];
const fn = (value) => (typeof value === 'function' ? fns.push(value) - 1 : -1);
const fnIndex = new Map();
const fn = (value) => {
if (typeof value !== 'function') return -1;
if (!fnIndex.has(value)) fnIndex.set(value, fns.push(value) - 1);
return fnIndex.get(value);
};
const attempt = (find, el) => {
try {
return find(el);
Expand Down
51 changes: 51 additions & 0 deletions src/main/inspector/adapter/reactTreeSource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { MAX_ROOT_SCAN } from '../constants';

/**
* Page-side, in the Components tree (`TREE_JS`): React's part. Its top is the roots' components (the hook's
* roots, else the containers React marks, the first `MAX_ROOT_SCAN` elements looked through); a node's
* children are the nearest component fibers under it, and it leads to its first element.
*/
export const REACT_TREE_JS = `
const reactRoots = () => {
const roots = new Set();
const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
if (hook && hook.renderers && typeof hook.getFiberRoots === 'function') {
for (const id of hook.renderers.keys()) for (const root of hook.getFiberRoots(id)) roots.add(root);
}
const elements = roots.size ? [] : document.querySelectorAll('*');
for (let i = 0; i < elements.length && i < ${MAX_ROOT_SCAN}; i++) {
const container = elements[i];
const key = Object.keys(container).find((k) => k.startsWith('__reactContainer$'));
const legacy = container._reactRootContainer && container._reactRootContainer._internalRoot;
if (key && container[key] && container[key].stateNode) roots.add(container[key].stateNode);
else if (legacy) roots.add(legacy);
}
return [...roots].filter((root) => root.current);
};
const reactKids = (fiber) => {
const out = [];
const walk = (parent) => {
for (let child = parent.child; child; child = child.sibling) {
if (isComponent(child)) out.push(child);
else walk(child);
}
};
walk(fiber);
return out;
};
const reactElement = (fiber) => {
if (fiber.stateNode instanceof Element) return fiber.stateNode;
for (let child = fiber.child; child; child = child.sibling) {
const found = reactElement(child);
if (found) return found;
}
return null;
};
const REACT_TREE = {
top: () => reactRoots().flatMap((root) => reactKids(root.current)),
kids: reactKids,
element: reactElement,
node: (f, fn) => ({ name: componentName(f.type), key: f.key == null ? null : String(f.key), fn: fn(renderFunction(f.type)) }),
same: (a, b) => a === b || a === b.alternate,
};
`;
18 changes: 14 additions & 4 deletions src/main/inspector/adapter/registrySource.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
import { ANGULAR_VIEW } from '../constants';
import { ANGULAR_REGISTRY_GLOBAL, ANGULAR_VIEW } from '../constants';

/** On an element or document: whether its page runs a production Angular build, whose components only its view registry leads to. */
export const NEEDS_REGISTRY_SOURCE = `function () {
/**
* On an element or document, for a page running a production Angular build (whose components only its view
* registry leads to): the registry, when it was found before and kept on the window (and still holds views);
* else null. Undefined for a page that needs none (no Angular, or a development build, with `window.ng`).
*/
export const KEPT_REGISTRY_SOURCE = `function () {
const ng = window.ng;
return !!document.querySelector('[ng-version]') && !(ng && typeof ng.getComponent === 'function');
if (!document.querySelector('[ng-version]') || (ng && typeof ng.getComponent === 'function')) return undefined;
const kept = Object.prototype.hasOwnProperty.call(window, '${ANGULAR_REGISTRY_GLOBAL}') ? window['${ANGULAR_REGISTRY_GLOBAL}'] : null;
return kept instanceof Map && kept.size ? kept : null;
}`;
/** On the registry found: kept on its page's window (`ANGULAR_REGISTRY_GLOBAL`), not enumerable. */
export const KEEP_REGISTRY_SOURCE = `function () {
Object.defineProperty(window, '${ANGULAR_REGISTRY_GLOBAL}', { configurable: true, value: this });
}`;
/** On an element or document: the Map prototype of its world, for `Runtime.queryObjects`. */
export const MAP_PROTOTYPE_SOURCE = 'function () { return Map.prototype; }';
Expand Down
79 changes: 30 additions & 49 deletions src/main/inspector/adapter/treeSource.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { MAX_ROOT_SCAN, MAX_TREE_NODES } from '../constants';
import { MAX_TREE_NODES } from '../constants';
import { REACT_TREE_JS } from './reactTreeSource';

/**
* Page-side Components tree for the adapter (`ADAPTER_SOURCE`), from the top:
Expand All @@ -11,41 +12,7 @@ import { MAX_ROOT_SCAN, MAX_TREE_NODES } from '../constants';
export const TREE_JS = `
// What an element belongs to, trying each framework in turn.
const findAt = (el) => [reactFind, vueFind, vue2Find, angularFind, elementFind].reduce((hit, find) => hit || attempt(find, el), null);
const reactRoots = () => {
const roots = new Set();
const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
if (hook && hook.renderers && typeof hook.getFiberRoots === 'function') {
for (const id of hook.renderers.keys()) for (const root of hook.getFiberRoots(id)) roots.add(root);
}
const elements = roots.size ? [] : document.querySelectorAll('*');
for (let i = 0; i < elements.length && i < ${MAX_ROOT_SCAN}; i++) {
const container = elements[i];
const key = Object.keys(container).find((k) => k.startsWith('__reactContainer$'));
const legacy = container._reactRootContainer && container._reactRootContainer._internalRoot;
if (key && container[key] && container[key].stateNode) roots.add(container[key].stateNode);
else if (legacy) roots.add(legacy);
}
return [...roots].filter((root) => root.current);
};
const reactKids = (fiber) => {
const out = [];
const walk = (parent) => {
for (let child = parent.child; child; child = child.sibling) {
if (isComponent(child)) out.push(child);
else walk(child);
}
};
walk(fiber);
return out;
};
const reactElement = (fiber) => {
if (fiber.stateNode instanceof Element) return fiber.stateNode;
for (let child = fiber.child; child; child = child.sibling) {
const found = reactElement(child);
if (found) return found;
}
return null;
};
${REACT_TREE_JS}
const vueKids = (instance) => {
const out = [];
const visit = (vnode) => {
Expand All @@ -68,13 +35,7 @@ export const TREE_JS = `
return null;
};
const TREE = {
react: {
top: () => reactRoots().flatMap((root) => reactKids(root.current)),
kids: reactKids,
element: reactElement,
node: (f, fn) => ({ name: componentName(f.type), key: f.key == null ? null : String(f.key), fn: fn(renderFunction(f.type)) }),
same: (a, b) => a === b || a === b.alternate,
},
react: REACT_TREE,
vue: {
top: () =>
Array.from(document.querySelectorAll('[data-v-app]'))
Expand All @@ -98,16 +59,27 @@ export const TREE_JS = `
}
};
const treeTop = () => Object.keys(TREE).flatMap((framework) => topOf(framework).map((ref) => ({ framework, ref })));
// A top node by its index, reading each framework's top only as far as it: one found in React's reads no other's.
const topEntry = (index) => {
let offset = 0;
for (const framework of Object.keys(TREE)) {
const top = topOf(framework);
if (index < offset + top.length) return { framework, ref: top[index - offset] };
offset += top.length;
}
return null;
};
const treeKids = (entry) => TREE[entry.framework].kids(entry.ref).map((ref) => ({ framework: entry.framework, ref }));
const treeAt = (path) => {
let level = treeTop();
let entry = null;
for (const index of path) {
if (!path.length) return { entry: null, level: treeTop() };
let entry = topEntry(path[0]);
let level = entry ? treeKids(entry) : [];
for (const index of path.slice(1)) {
entry = level[index];
if (!entry) return null;
level = treeKids(entry);
}
return { entry, level };
return entry ? { entry, level } : null;
};
const treeLevel = (path, fn) => {
const at = treeAt(path);
Expand All @@ -130,7 +102,16 @@ export const TREE_JS = `
if (index < 0) return null;
path.unshift(index);
}
const top = treeTop().findIndex((entry) => entry.framework === found.framework && same(entry.ref, found.refs[found.refs.length - 1]));
return top < 0 ? null : [top, ...path];
// Its top's index: the frameworks before its own count, the ones after aren't read.
let offset = 0;
for (const framework of Object.keys(TREE)) {
const top = topOf(framework);
if (framework === found.framework) {
const index = top.findIndex((ref) => same(ref, found.refs[found.refs.length - 1]));
return index < 0 ? null : [offset + index, ...path];
}
offset += top.length;
}
return null;
};
`;
19 changes: 11 additions & 8 deletions src/main/inspector/adapter/vueSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
* Page-side Vue 3 part of the adapter (`ADAPTER_SOURCE`). Development builds put
* the component on each element (`__vueParentComponent`); production builds
* don't, so the app's vnode tree is walked from the element it is mounted on
* (`_vnode`), as probed on Vue 3.5 (docs/INSPECTOR_RESEARCH.md §2).
* (`_vnode`), as probed on Vue 3.5 (docs/INSPECTOR_RESEARCH.md §2): only down
* the elements that hold the one looked for (an element's vnode holds its
* subtree), so a large app costs its depth, not its size.
*/
export const VUE_JS = `
const MAX_VNODES = 20000;
Expand All @@ -21,21 +23,22 @@ export const VUE_JS = `
let container = el;
while (container && !container._vnode) container = container.parentElement;
if (!container) return null;
const byElement = new Map();
// The deepest element holding it that a component rendered: the element itself, else its nearest such ancestor.
let hit = null;
let visited = 0;
const visit = (vnode, owner) => {
if (!vnode || typeof vnode !== 'object' || visited++ > MAX_VNODES) return;
if (vnode.component) return visit(vnode.component.subTree, vnode.component);
if (vnode.el && vnode.el.nodeType === 1 && !byElement.has(vnode.el)) byElement.set(vnode.el, { instance: owner, vnode });
// An element's vnode (a string type) holds its subtree; a fragment's or a teleport's doesn't.
if (typeof vnode.type === 'string' && vnode.el && vnode.el.nodeType === 1) {
if (!vnode.el.contains(el)) return;
if (owner) hit = { instance: owner, vnode };
}
if (Array.isArray(vnode.children)) vnode.children.forEach((child) => visit(child, owner));
if (vnode.suspense) visit(vnode.suspense.activeBranch, owner);
};
visit(container._vnode, null);
for (let node = el; node; node = node.parentElement) {
const hit = byElement.get(node);
if (hit && hit.instance) return { instance: hit.instance, vnode: hit.vnode, build: 'production' };
}
return null;
return hit && { instance: hit.instance, vnode: hit.vnode, build: 'production' };
};
const vueFind = (el) => {
const found = vueOwner(el);
Expand Down
9 changes: 9 additions & 0 deletions src/main/inspector/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ export const INSPECT_MODE = { pick: 'searchForNode', off: 'none' } as const;
export const ADAPTER_MODE = { summary: 'summary', describe: 'describe', set: 'set', tree: 'tree', locate: 'locate' } as const;
/** The internal property V8 gives a function's place under. */
export const FUNCTION_LOCATION = '[[FunctionLocation]]';
/** The most functions one read places (each is a call); the rest go unplaced. */
export const MAX_PLACED_FUNCTIONS = 1000;
/** The longest script URL kept for placing functions (a longer one, a data: URL, leaves its functions unplaced). */
export const MAX_SCRIPT_URL = 2048;
/** What a read says when its element is gone. */
export const PICK_GONE = 'That element is gone: the page moved on since it was picked.';
/** The View menu's Pick an Element item. */
Expand Down Expand Up @@ -86,6 +90,11 @@ export const LOADED_SCRIPT = /^https?:/;
* component's own view), its context (the component instance) and its id (the registry's key).
*/
export const ANGULAR_VIEW = { tView: 1, context: 8, id: 19, componentType: 1 } as const;
/**
* Where a page keeps Angular's view registry once it was found (a non-enumerable global of its window): the
* next read takes it from there instead of walking the heap, and it goes with the document.
*/
export const ANGULAR_REGISTRY_GLOBAL = '__consoleEditorNgRegistry';
/** The most steps a selector for a picked element takes up from it (to an ancestor with an id, or body). */
export const MAX_SELECTOR_STEPS = 16;
/** The most shadow roots a picked element's selectors go in through (the document's is one), and the longest selector taken. */
Expand Down
14 changes: 10 additions & 4 deletions src/main/inspector/reading/ScriptUrls.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { CdpTransport } from '../../engine/cdp';
import { CDP } from '../../engine/constants';
import { MAX_SCRIPT_URL } from '../constants';

/** What `Debugger.scriptParsed` says of a script that we keep. */
interface ParsedScript {
Expand All @@ -9,10 +10,10 @@ interface ParsedScript {
executionContextAuxData?: { frameId?: string; isDefault?: boolean };
}

/** A script of the session: its URL, the source map it names ('' for none), and the frame whose main world runs it (else null). */
/** A script of the session: its URL ('' for none, or one past `MAX_SCRIPT_URL`), whether it names a source map, and the frame whose main world runs it (else null). */
export interface ScriptRecord {
url: string;
sourceMap: string;
mapped: boolean;
frameId: string | null;
}

Expand All @@ -23,9 +24,12 @@ export interface ScriptRecord {
* replays it for every script already parsed: it is turned on just for that,
* with pauses skipped (a page's `debugger` statement can't stop it), then off
* again, whenever a script id isn't known yet or a frame's scripts are listed.
* Each replay replaces what was kept, so the scripts of documents gone go with
* them; a map named is kept as whether there is one (an inline map's URL holds
* the whole map).
*/
export class ScriptUrls {
private readonly scripts = new Map<string, ScriptRecord>();
private scripts = new Map<string, ScriptRecord>();
private refreshing: Promise<void> | null = null;

constructor(private readonly cdp: CdpTransport) {}
Expand All @@ -49,13 +53,15 @@ export class ScriptUrls {
}

private async replay(): Promise<void> {
const scripts = new Map<string, ScriptRecord>();
const off = this.cdp.on(CDP.Debugger.scriptParsed, (p: ParsedScript) => {
const context = p.executionContextAuxData;
this.scripts.set(p.scriptId, { url: p.url, sourceMap: p.sourceMapURL ?? '', frameId: context?.isDefault && context.frameId ? context.frameId : null });
scripts.set(p.scriptId, { url: p.url.length <= MAX_SCRIPT_URL ? p.url : '', mapped: !!p.sourceMapURL, frameId: context?.isDefault && context.frameId ? context.frameId : null });
});
try {
await this.cdp.send(CDP.Debugger.enable);
await this.cdp.send(CDP.Debugger.setSkipAllPauses, { skip: true });
this.scripts = scripts;
} finally {
off();
await this.cdp.send(CDP.Debugger.disable).catch(() => undefined);
Expand Down
17 changes: 11 additions & 6 deletions src/main/inspector/reading/angularRegistry.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
import type { EvaluateReply } from '../../console/types';
import type { CdpTransport } from '../../engine/cdp';
import { CDP } from '../../engine/constants';
import { FIND_REGISTRY_SOURCE, MAP_PROTOTYPE_SOURCE, NEEDS_REGISTRY_SOURCE } from '../adapter/registrySource';
import { FIND_REGISTRY_SOURCE, KEEP_REGISTRY_SOURCE, KEPT_REGISTRY_SOURCE, MAP_PROTOTYPE_SOURCE } from '../adapter/registrySource';

/**
* Angular's view registry, when the page of an element (or document) runs a production Angular build: a handle
* in `objectGroup`, found among every Map of the heap (`Runtime.queryObjects`, a walk of the heap: only then).
* Null when the page doesn't need it, or it can't be found.
* in `objectGroup`. Found once per document among every Map of the heap (`Runtime.queryObjects`, a walk of the
* heap), then kept on its window, where each later read takes it with one call. Null when the page doesn't
* need it, or it can't be found.
*/
export async function angularRegistry(transport: CdpTransport, objectId: string, objectGroup: string): Promise<string | null> {
const call = (id: string, functionDeclaration: string, returnByValue = false) => transport.send<EvaluateReply>(CDP.Runtime.callFunctionOn, { objectId: id, functionDeclaration, objectGroup, returnByValue, silent: true });
try {
const needs = await call(objectId, NEEDS_REGISTRY_SOURCE, true);
if (needs.result.value !== true) return null;
const kept = await call(objectId, KEPT_REGISTRY_SOURCE);
if (kept.result.objectId) return kept.result.objectId;
// Undefined: the page needs none; null: it needs one not found yet.
if (kept.result.subtype !== 'null') return null;
const prototype = await call(objectId, MAP_PROTOTYPE_SOURCE);
const { objects } = await transport.send<{ objects: { objectId?: string } }>(CDP.Runtime.queryObjects, { prototypeObjectId: prototype.result.objectId, objectGroup });
const registry = objects.objectId ? await call(objects.objectId, FIND_REGISTRY_SOURCE) : null;
return registry?.result.objectId ?? null;
const found = registry?.result.objectId ?? null;
if (found) await call(found, KEEP_REGISTRY_SOURCE, true);
return found;
} catch {
return null;
}
Expand Down
13 changes: 7 additions & 6 deletions src/main/inspector/reading/functionLocations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { CodeLocation } from '../../../shared/types';
import type { GetPropertiesReply } from '../../console/types';
import type { CdpTransport } from '../../engine/cdp';
import { CDP } from '../../engine/constants';
import { FUNCTION_LOCATION } from '../constants';
import { FUNCTION_LOCATION, MAX_PLACED_FUNCTIONS } from '../constants';
import type { ScriptUrls } from './ScriptUrls';

/** V8's place of a function: its script, and 0-based line and column. */
Expand All @@ -14,18 +14,19 @@ interface FunctionPlace {

/**
* Where each function of an array in the page is defined, by index: null for one
* V8 doesn't place (native, bound), or whose script has no URL (evaluated code).
* V8 doesn't place (native, bound), whose script has no URL (evaluated code), that
* is past `MAX_PLACED_FUNCTIONS`, or that went away meanwhile (the others are kept).
*/
export async function functionLocations(transport: CdpTransport, arrayId: string, scripts: ScriptUrls): Promise<Array<CodeLocation | null>> {
const { result } = await transport.send<GetPropertiesReply>(CDP.Runtime.getProperties, { objectId: arrayId, ownProperties: true });
const items = result.filter((p) => /^\d+$/.test(p.name));
const locations = items.map((): CodeLocation | null => null);
await Promise.all(
items.map(async (item) => {
items.slice(0, MAX_PLACED_FUNCTIONS).map(async (item) => {
if (!item.value?.objectId) return;
const reply = await transport.send<GetPropertiesReply>(CDP.Runtime.getProperties, { objectId: item.value.objectId, ownProperties: true });
const place = reply.internalProperties?.find((p) => p.name === FUNCTION_LOCATION)?.value?.value as FunctionPlace | undefined;
const url = place && (await scripts.url(place.scriptId));
const reply = await transport.send<GetPropertiesReply>(CDP.Runtime.getProperties, { objectId: item.value.objectId, ownProperties: true }).catch(() => null);
const place = reply?.internalProperties?.find((p) => p.name === FUNCTION_LOCATION)?.value?.value as FunctionPlace | undefined;
const url = place && (await scripts.url(place.scriptId).catch(() => null));
if (place && url) locations[Number(item.name)] = { url, line: place.lineNumber, column: place.columnNumber };
}),
);
Expand Down
Loading
Loading