diff --git a/devtools/projects/ng-devtools-backend/src/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/BUILD.bazel index bae52411c3d..a55ca9e5aad 100644 --- a/devtools/projects/ng-devtools-backend/src/BUILD.bazel +++ b/devtools/projects/ng-devtools-backend/src/BUILD.bazel @@ -8,7 +8,7 @@ ts_project( deps = [ "//devtools/projects/ng-devtools-backend/src/lib", "//devtools/projects/ng-devtools-backend/src/lib:client_event_subscribers", - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest", "//devtools/projects/ng-devtools-backend/src/lib/router-tree", "//devtools/projects/ng-devtools-backend/src/lib/shared:interfaces", ], diff --git a/devtools/projects/ng-devtools-backend/src/lib/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/lib/BUILD.bazel index 5d34668430b..c248ea3b6c0 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/BUILD.bazel +++ b/devtools/projects/ng-devtools-backend/src/lib/BUILD.bazel @@ -47,9 +47,12 @@ ts_project( "//devtools/projects/ng-devtools-backend/src/lib/component-inspector", "//devtools/projects/ng-devtools-backend/src/lib/config", "//devtools/projects/ng-devtools-backend/src/lib/console:set-console-reference", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest", "//devtools/projects/ng-devtools-backend/src/lib/directive-forest:manager", - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/directive-state", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils:directive", "//devtools/projects/ng-devtools-backend/src/lib/hydration:hydration-overlays", + "//devtools/projects/ng-devtools-backend/src/lib/injector-tree", "//devtools/projects/ng-devtools-backend/src/lib/profiling", "//devtools/projects/ng-devtools-backend/src/lib/profiling/cd-analyzer", "//devtools/projects/ng-devtools-backend/src/lib/profiling/profiler", diff --git a/devtools/projects/ng-devtools-backend/src/lib/client-event-subscribers.ts b/devtools/projects/ng-devtools-backend/src/lib/client-event-subscribers.ts index 170fb702892..e59140cc207 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/client-event-subscribers.ts +++ b/devtools/projects/ng-devtools-backend/src/lib/client-event-subscribers.ts @@ -36,24 +36,26 @@ import { import {ComponentInspector} from './component-inspector/component-inspector'; import {setConsoleReference} from './console/set-console-reference'; +import {queryDirectiveForest} from './directive-forest'; +import { + getLatestDirectiveState, + logDirectiveValue, + updateDirectiveState, +} from './directive-forest/directive-state/directive-state'; +import {getDirectiveForestManager} from './directive-forest/manager'; +import {getDirectiveCdStrategy} from './directive-forest/utils/directive'; +import {loadHydrationOverlays} from './hydration/hydration-overlays'; import { - getDirectiveCdStrategy, getElementInjectorElement, getInjectorFromElementNode, getInjectorProviders, getInjectorResolutionPath, - getLatestComponentState, idToInjector, isElementInjector, - logValue, nodeInjectorToResolutionPath, - queryDirectiveForest, serializeProviderRecord, serializeResolutionPath, - updateState, -} from './directive-forest/component-tree/component-tree'; -import {getDirectiveForestManager} from './directive-forest/manager'; -import {loadHydrationOverlays} from './hydration/hydration-overlays'; +} from './injector-tree/injector-tree'; import {start as startProfiling, stop as stopProfiling} from './profiling/capture'; import {loadCdDataStream, loadCdHighlighting} from './profiling/cd-analyzer'; import {loadPerformanceTrack} from './profiling/performance-track'; @@ -119,8 +121,8 @@ export const subscribeToClientEvents = ( messageBus.on('getSignalNestedProperties', getSignalNestedPropertiesCallback(messageBus)); - messageBus.on('updateState', updateState); - messageBus.on('logValue', logValue); + messageBus.on('updateState', updateDirectiveState); + messageBus.on('logValue', logDirectiveValue); messageBus.on('getInjectorProviders', getInjectorProvidersCallback(messageBus)); @@ -194,7 +196,7 @@ const getLatestComponentExplorerViewCallback = return; } - const state = getLatestComponentState(query, getDirectiveForestManager().getDirectiveForest()); + const state = getLatestDirectiveState(query, getDirectiveForestManager().getDirectiveForest()); if (state) { const {directiveProperties} = state; diff --git a/devtools/projects/ng-devtools-backend/src/lib/component-inspector/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/lib/component-inspector/BUILD.bazel index 01c016b2a60..f66e31d1ba8 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/component-inspector/BUILD.bazel +++ b/devtools/projects/ng-devtools-backend/src/lib/component-inspector/BUILD.bazel @@ -6,8 +6,9 @@ ts_project( name = "component-inspector", srcs = ["component-inspector.ts"], deps = [ + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest", "//devtools/projects/ng-devtools-backend/src/lib/directive-forest:manager", - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils:directive", "//devtools/projects/ng-devtools-backend/src/lib/profiling", "//devtools/projects/ng-devtools-backend/src/lib/shared:interfaces", "//devtools/projects/ng-devtools-backend/src/lib/shared/highlighter", diff --git a/devtools/projects/ng-devtools-backend/src/lib/component-inspector/component-inspector.ts b/devtools/projects/ng-devtools-backend/src/lib/component-inspector/component-inspector.ts index 5f1c95b7761..35e01a5daae 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/component-inspector/component-inspector.ts +++ b/devtools/projects/ng-devtools-backend/src/lib/component-inspector/component-inspector.ts @@ -8,12 +8,9 @@ import {ElementPosition} from '../../../../protocol'; -import { - findDirectiveAndHost, - findNodeInForest, - getDirectiveName, -} from '../directive-forest/component-tree/component-tree'; +import {findNodeInForest} from '../directive-forest'; import {getDirectiveForestManager} from '../directive-forest/manager'; +import {findDirectiveAndHost, getDirectiveName} from '../directive-forest/utils/directive'; import {Highlight, inspectElementHighlightTemplate} from '../shared/highlighter/highlights'; import {highlightElement} from '../shared/highlighter'; import {ComponentTreeNode} from '../shared/interfaces'; diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/BUILD.bazel index fcd51565529..dc53a56d2bd 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/BUILD.bazel +++ b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/BUILD.bazel @@ -1,4 +1,4 @@ -load("//devtools/tools:defaults.bzl", "ts_project") +load("//devtools/tools:defaults.bzl", "ts_project", "ts_test_library", "zoneless_web_test_suite") package(default_visibility = ["//devtools:__subpackages__"]) @@ -9,6 +9,10 @@ ts_project( ], deps = [ "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/tree-strategies", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils:app-roots", + "//devtools/projects/ng-devtools-backend/src/lib/shared:interfaces", + "//devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api", + "//devtools/projects/protocol", ], ) @@ -30,3 +34,22 @@ ts_project( "//devtools/projects/protocol", ], ) + +ts_test_library( + name = "test_lib", + srcs = [ + "directive-forest.spec.ts", + ], + deps = [ + ":directive-forest", + "//:node_modules/@angular/core", + "//:node_modules/jasmine", + ], +) + +zoneless_web_test_suite( + name = "test", + deps = [ + ":test_lib", + ], +) diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/BUILD.bazel deleted file mode 100644 index 1505cfddd05..00000000000 --- a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/BUILD.bazel +++ /dev/null @@ -1,45 +0,0 @@ -load("//devtools/tools:defaults.bzl", "ts_project", "ts_test_library", "zoneless_web_test_suite") - -package(default_visibility = ["//visibility:public"]) - -ts_project( - name = "get-roots", - srcs = ["get-roots.ts"], -) - -ts_project( - name = "component-tree", - srcs = ["component-tree.ts"], - deps = [ - ":get-roots", - "//:node_modules/@angular/core", - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest", - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest:core-enums", - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/property-mutation", - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/tree-strategies", - "//devtools/projects/ng-devtools-backend/src/lib/shared:interfaces", - "//devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api", - "//devtools/projects/ng-devtools-backend/src/lib/shared/state-serializer", - "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:error", - "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:general", - "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:log", - "//devtools/projects/protocol", - ], -) - -ts_test_library( - name = "test_lib", - srcs = glob(["*.spec.ts"]), - deps = [ - ":component-tree", - ":get-roots", - "//:node_modules/@angular/core", - "//:node_modules/jasmine", - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest:core-enums", - ], -) - -zoneless_web_test_suite( - name = "test", - deps = [":test_lib"], -) diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/component-tree.spec.ts b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/component-tree.spec.ts deleted file mode 100644 index 5c061deba23..00000000000 --- a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/component-tree.spec.ts +++ /dev/null @@ -1,207 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.dev/license - */ - -import { - Injector, - ɵExternalCoreGlobalUtils, - ɵProviderRecord as ProviderRecord, - InjectionToken, -} from '@angular/core'; -import { - getDirectiveCdStrategy, - getInjectorFromElementNode, - getRootElements, - serializeProviderRecord, -} from './component-tree'; -import {ChangeDetectionStrategy, Framework} from '../core-enums'; - -type Ng = ɵExternalCoreGlobalUtils; -const NG_VERSION = 'ng-version'; -const VERSION = '0.0.0-PLACEHOLDER'; - -function setNgVersion(element: Element) { - element.setAttribute(NG_VERSION, VERSION); -} - -function createRoot() { - const root = document.createElement('div'); - setNgVersion(root); - return root; -} - -describe('component-tree', () => { - afterEach(() => { - delete (globalThis as any).ng; - }); - - describe('getInjectorFromElementNode', () => { - it('returns injector', () => { - const injector = Injector.create({ - providers: [], - }); - - const ng: Partial = { - getInjector: jasmine.createSpy('getInjector').and.returnValue(injector), - }; - (globalThis as any).ng = ng; - - const el = document.createElement('div'); - expect(getInjectorFromElementNode(el)).toBe(injector); - expect(ng.getInjector).toHaveBeenCalledOnceWith(el); - }); - - it('returns `null` when `getInjector` is not supported', () => { - (globalThis as any).ng = {}; - - const el = document.createElement('div'); - expect(getInjectorFromElementNode(el)).toBeNull(); - }); - }); - - describe('getRootElements', () => { - beforeEach(() => { - const ng: Partial = { - getComponent: jasmine.createSpy('getComponent').and.callFake((element: HTMLElement) => { - // Will treat only `ng-*` elements as Angular components. - if (element.tagName.toLowerCase().startsWith('ng-')) { - return element; - } - return null; - }), - }; - (window as any).ng = ng; - }); - - afterEach(() => { - document.body.replaceChildren(); - document.body.removeAttribute(NG_VERSION); - delete (window as any).ng; - }); - - it('should return root element', () => { - const rootElement = createRoot(); - const childElement = createRoot(); - - rootElement.appendChild(childElement); - document.body.appendChild(rootElement); - - const roots = getRootElements(); - - expect(roots.length).toEqual(1); - expect(roots.pop()).toEqual(rootElement); - }); - - it('should return multiple sibling roots', () => { - const firstRoot = createRoot(); - const secondRoot = createRoot(); - - document.body.appendChild(firstRoot); - document.body.appendChild(secondRoot); - - const roots = getRootElements(); - - expect(roots.length).toEqual(2); - expect(roots).toContain(firstRoot); - expect(roots).toContain(secondRoot); - }); - - it('should only return document.body when document.body is the root', () => { - setNgVersion(document.body); - const child1 = createRoot(); - document.body.appendChild(child1); - const roots = getRootElements(); - expect(roots.length).toEqual(1); - expect(roots).toContain(document.body); - }); - - it('should return all root elements with all non-application root components', () => { - const rootElement = createRoot(); - const childElement = createRoot(); - const nonAppRootCmp = document.createElement('ng-cmp'); - - rootElement.appendChild(childElement); - document.body.appendChild(rootElement); - document.body.appendChild(nonAppRootCmp); - - const roots = getRootElements(); - - expect(roots.length).toEqual(2); - expect(roots).toEqual([rootElement, nonAppRootCmp]); - }); - }); - - describe('serializeProviderRecord', () => { - it('should return "internal" type for internal tokens', () => { - const internalTokenNames = [ - 'ElementRef', - 'Renderer2', - 'ViewContainerRef', - 'DestroyRef', - 'ChangeDetectorRef', - 'Injector', - ]; - - internalTokenNames.forEach((tokenName, index) => { - const token = () => {}; - Object.defineProperty(token, 'name', {value: tokenName}); - const providerRecord: any = { - provider: () => {}, - token, - isViewProvider: false, - }; - const result = serializeProviderRecord(providerRecord, index); - expect(result.type).toBe('internal'); - expect(result.token).toBe(tokenName); - }); - }); - - it('should return "type" for non-internal function providers', () => { - const token = () => {}; - Object.defineProperty(token, 'name', {value: 'MyCustomService'}); - const providerRecord: any = { - provider: () => {}, - token, - isViewProvider: false, - }; - const result = serializeProviderRecord(providerRecord, 0); - expect(result.type).toBe('type'); - expect(result.token).toBe('MyCustomService'); - }); - - it('should handle injection tokens', () => { - const result = serializeProviderRecord( - { - token: new InjectionToken('FOO'), - isViewProvider: false, - } as ProviderRecord, - 0, - ); - - expect(result.token).toBe('InjectionToken (FOO)'); - }); - }); - - describe('getDirectiveCdStrategy', () => { - it('returns change detection strategy when passed valid component', () => { - const ng: Partial = { - getDirectiveMetadata: jasmine.createSpy('getDirectiveMetadata').and.returnValue({ - framework: Framework.Angular, - changeDetection: ChangeDetectionStrategy.OnPush, - } as any), - }; - (globalThis as any).ng = ng; - - const result = getDirectiveCdStrategy({ - instance: {}, - name: 'Foo', - isElement: false, - }); - expect(result).toBe('ng-on-push'); - }); - }); -}); diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/component-tree.ts b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/component-tree.ts deleted file mode 100644 index effe57afb03..00000000000 --- a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/component-tree.ts +++ /dev/null @@ -1,866 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.dev/license - */ - -import type { - ɵAcxComponentDebugMetadata as AcxComponentDebugMetadata, - ɵAngularComponentDebugMetadata as AngularComponentDebugMetadata, - ClassProvider, - ExistingProvider, - FactoryProvider, - InjectOptions, - InjectionToken, - Injector, - ɵProviderRecord as ProviderRecord, - Type, - ValueProvider, -} from '@angular/core'; -import {buildDirectiveForestWithStrategy} from '..'; -import { - ChangeDetection, - ComponentExplorerViewQuery, - DirectiveMetadata, - DirectivePosition, - DirectivesProperties, - ElementPosition, - PropertyQueryTypes, - SerializedInjectedService, - SerializedInjector, - SerializedProviderRecord, - UpdatedStateData, -} from '../../../../../protocol'; -import { - ComponentInstanceType, - ComponentTreeNode, - DirectiveInstanceType, -} from '../../shared/interfaces'; -import { - ngDebugApiIsSupported, - ngDebugClient, - ngDebugDependencyInjectionApiIsSupported, -} from '../../shared/ng-debug-api/ng-debug-api'; -import { - deeplySerializeSelectedProperties, - serializeDirectiveState, -} from '../../shared/state-serializer/state-serializer'; -import {unwrapSignal} from '../../shared/utils/general'; -import {AcxChangeDetectionStrategy, ChangeDetectionStrategy, Framework} from '../core-enums'; -import {mutateNestedProp} from '../property-mutation/property-mutation'; -import {getLViewFromDirectiveOrElementInstance} from '../tree-strategies/ltree'; -import {getAppRoots} from './get-roots'; -import {log} from '../../shared/utils/log'; -import {AngularDevtoolsError} from '../../shared/utils/error'; - -export const injectorToId = new WeakMap(); -export const nodeInjectorToResolutionPath = new WeakMap(); -export const idToInjector = new Map>(); -const injectorFinalizer = new FinalizationRegistry((id) => { - idToInjector.delete(id); -}); -let injectorId = 0; - -export function getInjectorId() { - return `${injectorId++}`; -} - -function getOrCreateInjectorId(key: Injector | HTMLElement, injector: Injector): string { - if (!injectorToId.has(key)) { - const newId = getInjectorId(); - injectorToId.set(key, newId); - idToInjector.set(newId, new WeakRef(injector)); - injectorFinalizer.register(injector, newId); - } - return injectorToId.get(key)!; -} - -const INTERNAL_TOKENS = [ - 'ElementRef', - 'Renderer2', - 'ViewContainerRef', - 'DestroyRef', - 'ChangeDetectorRef', - 'Injector', -]; - -export function getInjectorMetadata( - injector: Injector, -): ReturnType['ɵgetInjectorMetadata']>> { - return ngDebugClient().ɵgetInjectorMetadata?.(injector) ?? null; -} - -export function getInjectorResolutionPath(injector: Injector): Injector[] { - const ng = ngDebugClient(); - if (!ngDebugApiIsSupported(ng, 'ɵgetInjectorResolutionPath')) { - return []; - } - - return ng.ɵgetInjectorResolutionPath(injector) ?? []; -} - -export function getInjectorFromElementNode(element: Node): Injector | null { - try { - return ngDebugClient().getInjector?.(element) ?? null; - } catch { - return null; - } -} - -function getDirectivesFromElement(element: HTMLElement): { - component: unknown | null; - directives: unknown[]; -} { - const ng = ngDebugClient(); - let component = null; - if (element instanceof Element && ngDebugApiIsSupported(ng, 'getComponent')) { - component = ng.getComponent(element); - } - - return { - component, - directives: ngDebugClient().getDirectives?.(element) ?? [], - }; -} - -export const getLatestComponentState = ( - query: ComponentExplorerViewQuery, - directiveForest?: ComponentTreeNode[], -): {directiveProperties: DirectivesProperties} | undefined => { - // if a directive forest is passed in we don't have to build the forest again. - directiveForest = directiveForest ?? buildDirectiveForest(); - - const node = queryDirectiveForest(query.selectedElement, directiveForest); - if (!node) { - return; - } - - const directiveProperties: DirectivesProperties = {}; - - const injector = getInjectorFromElementNode(node.nativeElement!); - - const injectors = injector ? getInjectorResolutionPath(injector) : []; - const resolutionPathWithProviders = !ngDebugDependencyInjectionApiIsSupported() - ? [] - : injectors.map((injector) => ({ - injector, - providers: getInjectorProviders(injector), - })); - const populateResultSet = (dir: DirectiveInstanceType | ComponentInstanceType) => { - const {instance, name} = dir; - const metadata = getDirectiveMetadata(instance); - if (injector && metadata.framework === Framework.Angular) { - metadata.dependencies = getDependenciesForDirective( - injector, - resolutionPathWithProviders, - instance.constructor, - ); - } - - if (query.propertyQuery.type === PropertyQueryTypes.All) { - directiveProperties[dir.name] = { - props: serializeDirectiveState(instance), - metadata, - }; - } - - if (query.propertyQuery.type === PropertyQueryTypes.Specified) { - directiveProperties[name] = { - props: deeplySerializeSelectedProperties( - instance, - query.propertyQuery.properties[name] || [], - ), - metadata, - }; - } - }; - - node.directives?.forEach((dir) => populateResultSet(dir)); - if (node.component) { - populateResultSet(node.component); - } - - return { - directiveProperties, - }; -}; - -function serializeElementInjectorWithId(injector: Injector): SerializedInjector | null { - const element = getElementInjectorElement(injector); - const id = getOrCreateInjectorId(element, injector); - - const serializedInjector = serializeInjector(injector); - if (serializedInjector === null) { - return null; - } - - return {id, ...serializedInjector}; -} - -function serializeInjectorWithId(injector: Injector): SerializedInjector | null { - if (isElementInjector(injector)) { - return serializeElementInjectorWithId(injector); - } else { - return serializeEnvironmentInjectorWithId(injector); - } -} - -function serializeEnvironmentInjectorWithId(injector: Injector): SerializedInjector | null { - const id = getOrCreateInjectorId(injector, injector); - - const serializedInjector = serializeInjector(injector); - if (serializedInjector === null) { - return null; - } - - return {id, ...serializedInjector}; -} - -const enum DirectiveMetadataKey { - INPUTS = 'inputs', - OUTPUTS = 'outputs', - ENCAPSULATION = 'encapsulation', - CHANGE_DETECTION = 'changeDetection', -} - -// Gets directive metadata. For newer versions of Angular (v12+) it uses -// the global `getDirectiveMetadata`. For prior versions of the framework -// the method directly interacts with the directive/component definition. -function getDirectiveMetadata(dir: any): DirectiveMetadata { - const getMetadata = ngDebugClient().getDirectiveMetadata; - const metadata = dir ? getMetadata?.(dir) : null; - if (metadata) { - const {framework} = metadata; - switch (framework) { - case undefined: // Back compat, older Angular versions did not set `framework`. - case Framework.Angular: { - const meta = metadata as typeof metadata & Partial; - return { - framework: Framework.Angular, - name: meta.name, - inputs: meta.inputs, - outputs: meta.outputs, - encapsulation: meta.encapsulation, - changeDetection: meta.changeDetection, - }; - } - case Framework.ACX: { - const meta = metadata as typeof metadata & Partial; - return { - framework: Framework.ACX, - name: meta.name, - inputs: meta.inputs, - outputs: meta.outputs, - encapsulation: meta.encapsulation, - changeDetection: meta.changeDetection, - }; - } - case Framework.Wiz: { - return { - framework: Framework.Wiz, - name: metadata.name, - props: metadata.props, - }; - } - default: { - throw new AngularDevtoolsError(`Unknown framework: "${framework}".`); - } - } - } - - // Used in older Angular versions, prior to the introduction of `getDirectiveMetadata`. - const safelyGrabMetadata = (key: DirectiveMetadataKey) => { - try { - return dir.constructor.ɵcmp ? dir.constructor.ɵcmp[key] : dir.constructor.ɵdir[key]; - } catch { - log.warn(`Could not find metadata for key: ${key} in directive:`, dir); - return undefined; - } - }; - - return { - framework: Framework.Angular, - inputs: safelyGrabMetadata(DirectiveMetadataKey.INPUTS), - outputs: safelyGrabMetadata(DirectiveMetadataKey.OUTPUTS), - encapsulation: safelyGrabMetadata(DirectiveMetadataKey.ENCAPSULATION), - changeDetection: safelyGrabMetadata(DirectiveMetadataKey.CHANGE_DETECTION), - }; -} - -export function getDirectiveCdStrategy(dir: ComponentInstanceType): ChangeDetection | undefined { - const metadata = getDirectiveMetadata(dir.instance); - - switch (metadata.framework) { - case Framework.Angular: - switch (metadata.changeDetection) { - case ChangeDetectionStrategy.OnPush: - return 'ng-on-push'; - case ChangeDetectionStrategy.Eager: - return 'ng-eager'; - } - - case Framework.ACX: - switch (metadata.changeDetection) { - case AcxChangeDetectionStrategy.Default: - return 'acx-default'; - case AcxChangeDetectionStrategy.OnPush: - return 'acx-on-push'; - } - - case Framework.Wiz: - return undefined; - - default: - throw new AngularDevtoolsError( - `Unknown framework: "${(metadata as {framework: string}).framework}".`, - ); - } -} - -export function getInjectorProviders(injector: Injector) { - if (isNullInjector(injector)) { - return []; - } - - return ngDebugClient().ɵgetInjectorProviders!(injector); -} - -const getDependenciesForDirective = ( - injector: Injector, - resolutionPath: {injector: Injector; providers: ProviderRecord[]}[], - directive: any, -): SerializedInjectedService[] => { - const ng = ngDebugClient(); - if (!ngDebugApiIsSupported(ng, 'ɵgetDependenciesFromInjectable')) { - return []; - } - - let dependencies = ng.ɵgetDependenciesFromInjectable(injector, directive)?.dependencies ?? []; - const uniqueServices = new Set(); - const serializedInjectedServices: SerializedInjectedService[] = []; - - let position = 0; - for (const dependency of dependencies) { - const providedIn = dependency.providedIn; - const foundInjectorIndex = resolutionPath.findIndex((node) => node.injector === providedIn); - - if (foundInjectorIndex === -1) { - position++; - continue; - } - - const providers = resolutionPath[foundInjectorIndex].providers; - const foundProvider = providers.find((provider) => provider.token === dependency.token); - - // the dependency resolution path is - // the path from the root injector to the injector that provided the dependency (1) - // + - // the import path from the providing injector to the feature module that provided the - // dependency (2) - const dependencyResolutionPath: SerializedInjector[] = [ - // (1) - ...resolutionPath - .slice(0, foundInjectorIndex + 1) - .map((node) => serializeInjectorWithId(node.injector)!), - - // (2) - // We slice the import path to remove the first element because this is the same - // injector as the last injector in the resolution path. - ...(foundProvider?.importPath ?? []).slice(1).map((node): SerializedInjector => { - return { - type: 'imported-module', - name: valueToLabel(node), - id: getInjectorId(), - }; - }), - ]; - - let flags = dependency.flags as InjectOptions; - let flagToken = ''; - if (flags !== undefined) { - if (typeof flags === 'number') { - flags = { - optional: !!(flags & 8), - skipSelf: !!(flags & 4), - self: !!(flags & 2), - host: !!(flags & 1), - }; - } - flagToken = (['optional', 'skipSelf', 'self', 'host'] as (keyof InjectOptions)[]) - .filter((key) => flags[key]) - .join('-'); - } - - const serviceKey = `${dependency.token}-${flagToken}`; - if (!uniqueServices.has(serviceKey)) { - uniqueServices.add(serviceKey); - - const service = { - token: valueToLabel(dependency.token), - value: valueToLabel(dependency.value), - flags, - position: [position], - resolutionPath: dependencyResolutionPath, - }; - - serializedInjectedServices.push(service); - } - - position++; - } - - return serializedInjectedServices; -}; - -const valueToLabel = (value: any): string => { - if (isInjectionToken(value)) { - const token = value.toString(); - - // This logic relies on the current InjectionToken.toString implementation. - if (token.startsWith('InjectionToken')) { - const tokenName = token.replace('InjectionToken', '').trim(); - return `InjectionToken (${tokenName})`; - } - return token; - } - - if (typeof value === 'object') { - return stripUnderscore(value.constructor.name); - } - - if (typeof value === 'function') { - return stripUnderscore(value.name); - } - - if (typeof value !== 'string') { - return String(value); - } - - return stripUnderscore(value); -}; - -function stripUnderscore(str: string): string { - if (str.startsWith('_')) { - return str.slice(1); - } - - return str; -} - -export function serializeInjector(injector: Injector): Omit | null { - const metadata = getInjectorMetadata(injector); - - if (metadata === null) { - log.error('Could not serialize injector.', injector); - return null; - } - - const providers = getInjectorProviders(injector).length; - - if (metadata.type === 'null') { - return {type: 'null', name: 'Null Injector', providers: 0}; - } - - if (metadata.type === 'element') { - const source = metadata.source as HTMLElement; - const name = stripUnderscore(elementToDirectiveNames(source)[0]); - - return {type: 'element', name, providers}; - } - - if (metadata.type === 'environment') { - if ((injector as any).scopes instanceof Set) { - if ((injector as any).scopes.has('platform')) { - return {type: 'environment', name: 'Platform', providers}; - } - - if ((injector as any).scopes.has('root')) { - return {type: 'environment', name: 'Root', providers}; - } - } - - return {type: 'environment', name: stripUnderscore(metadata.source ?? ''), providers}; - } - - log.error('Could not serialize injector.', injector); - return null; -} - -export function serializeProviderRecord( - providerRecord: ProviderRecord, - index: number, - hasImportPath = false, -): SerializedProviderRecord { - let type: 'type' | 'class' | 'value' | 'factory' | 'existing' | 'internal' = 'type'; - let multi = false; - - if (typeof providerRecord.provider === 'object') { - if ((providerRecord.provider as ClassProvider).useClass !== undefined) { - type = 'class'; - } else if ((providerRecord.provider as ValueProvider).useValue !== undefined) { - type = 'value'; - } else if ((providerRecord.provider as FactoryProvider).useFactory !== undefined) { - type = 'factory'; - } else if ((providerRecord.provider as ExistingProvider).useExisting !== undefined) { - type = 'existing'; - } - - if (providerRecord.provider.multi !== undefined) { - multi = providerRecord.provider.multi; - } - } else if (typeof providerRecord.provider === 'function') { - if (INTERNAL_TOKENS.includes((providerRecord.token as Type).name)) { - type = 'internal'; - } - } - - const serializedProvider: { - token: string; - type: typeof type; - multi: boolean; - isViewProvider: boolean; - index: number; - importPath?: string[]; - } = { - token: valueToLabel(providerRecord.token), - type, - multi, - isViewProvider: providerRecord.isViewProvider, - index, - }; - - if (hasImportPath) { - serializedProvider['importPath'] = (providerRecord.importPath ?? []).map((injector) => - valueToLabel(injector), - ); - } - - return serializedProvider; -} - -function elementToDirectiveNames(element: HTMLElement): string[] { - const {component, directives} = getDirectivesFromElement(element); - return [component, ...directives] - .map((dir) => dir?.constructor?.name ?? '') - .filter((dir) => !!dir); -} - -export function getElementInjectorElement(elementInjector: Injector): HTMLElement { - if (!isElementInjector(elementInjector)) { - throw new AngularDevtoolsError('Injector is not an element injector'); - } - - return getInjectorMetadata(elementInjector)!.source as HTMLElement; -} - -function isInjectionToken(token: Type | InjectionToken): boolean { - return token.constructor.name === 'InjectionToken'; -} - -export function isElementInjector(injector: Injector) { - const metadata = getInjectorMetadata(injector); - return metadata !== null && metadata.type === 'element'; -} - -function isNullInjector(injector: Injector) { - const metadata = getInjectorMetadata(injector); - return metadata !== null && metadata.type === 'null'; -} - -const getRootLViewsHelper = (element: Element, rootLViews = new Set()): Set => { - if (!(element instanceof HTMLElement)) { - return rootLViews; - } - const lView = getLViewFromDirectiveOrElementInstance(element); - if (lView) { - rootLViews.add(lView); - return rootLViews; - } - for (let i = 0; i < element.children.length; i++) { - getRootLViewsHelper(element.children[i], rootLViews); - } - return rootLViews; -}; - -/** Gets the all the root components in the Dom, including those outside the application root */ -export function getRootElements(): Element[] { - if (!ngDebugClient().getComponent) { - // If the ngDebugClient does not support getComponent, we cannot proceed. - return []; - } - - const roots = getAppRoots(); - const rootSet = new Set(roots); - - // Traverse the DOM tree for other non application root Angular components. - // Pass in the existing roots to inform the traversal that we can skip those paths. - discoverNonApplicationRootComponents(document.body, rootSet); - - return [...rootSet]; -} - -/** - * Warning: This function mutates the `roots` arg! - * - * Recursively traverse the DOM tree to find all Angular component root elements. - * - * This function starts from the given element and traverses its children. - * When it finds an Angular component, it adds that element to the `roots` set. - * - * If we discover an angular component that we've already added to the `roots` set, - * we skip traversing its children. This is to ensure that we only collect unique root elements. - * - * - * Example: - * - * Lets say we have the following DOM structure: - * - * ```html - * - * ... - * ... - * - * - * ... - * - * - *
Not an angular component
- * - * - * ``` - * - * In this case, `app-root-1` and `app-root-2` are the root elements of Angular components. - * The `mat-dialog` is a non application root Angular component. - * - * We can discover the roots by searching for ng-version. This gives us a set of paths that we can skip traversing. - * - * ```ts - * const rootSet = new Set(getAppRoots()); - * console.log(rootSet); - * // Set(, ) - * discoverNonApplicationRootComponents(document.body, rootSet); - * console.log(rootSet); - * // Set(, , ) - * ``` - * - * ```md - * - * traversing document.body.children: - * - child: - * - Since we have this already in the `roots` set, we skip traversing its children. - * - child: - * - Since we have this already in the `roots` set, we skip traversing its children. - * - child: - * - Since this is not in the `roots` set, we check if it is an Angular component. - * - Since it is, we add it to the `roots` set and break the loop. - * - child:
- * - Since this is not an Angular component, we traverse its children to see if we can find any Angular components. - * - * ``` - * - * @param element The current DOM element being traversed. - * @param roots A set of root elements found during the traversal. - */ -function discoverNonApplicationRootComponents(element: Element, roots: Set): void { - if (roots.has(element)) { - return; - } - const children = Array.from(element.children); - for (const child of children) { - if (roots.has(child)) { - continue; - } - - const ng = ngDebugClient(); - if (ng.getComponent && ng.getComponent(child)) { - roots.add(child); - // If the child is an Angular component, we can skip traversing its children. - continue; - } - - discoverNonApplicationRootComponents(child, roots); - } -} - -export const buildDirectiveForest = (): ComponentTreeNode[] => { - const ng = ngDebugClient(); - if ((ng as any).getComponentForest) { - const forest: ComponentTreeNode[] = (ng as any).getComponentForest(); - const frontier = [...forest]; - while (frontier.length) { - const node = frontier.pop()!; - const rawNode = node as any; - node.tagName ??= rawNode.element ?? rawNode.nativeElement?.nodeName.toLowerCase() ?? ''; - node.component!.isElement ??= false; - for (const child of node.children) { - frontier.push(child); - } - } - return forest; - } - return buildDirectiveForestWithStrategy(getRootElements()); -}; - -// Based on an ElementID we return a specific component node. -// If we can't find any, we return null. -export const queryDirectiveForest = ( - position: ElementPosition, - forest: ComponentTreeNode[], -): ComponentTreeNode | null => { - if (!position.length) { - return null; - } - let node: null | ComponentTreeNode = null; - for (const i of position) { - node = forest[i]; - if (!node) { - return null; - } - forest = node.children; - } - if (node?.controlFlowBlock) { - return null; - } - return node; -}; - -export const findNodeInForest = ( - position: ElementPosition, - forest: ComponentTreeNode[], -): Element | null => { - const foundComponent: ComponentTreeNode | null = queryDirectiveForest(position, forest); - const nativeElement = foundComponent?.nativeElement; - return nativeElement instanceof Element ? nativeElement : null; -}; - -export const findNodeFromSerializedPosition = ( - serializedPosition: string, -): ComponentTreeNode | null => { - const position: number[] = JSON.parse(serializedPosition); - return queryDirectiveForest(position, buildDirectiveForest()); -}; - -export const updateState = (updatedStateData: UpdatedStateData): void => { - const ng = ngDebugClient(); - const node = queryDirectiveForest(updatedStateData.directiveId.element, buildDirectiveForest()); - if (!node) { - log.warn( - 'Could not update the state of component', - updatedStateData, - 'because the component was not found', - ); - return; - } - if (node.directives && updatedStateData.directiveId.directive !== undefined) { - const directive = node.directives[updatedStateData.directiveId.directive].instance; - mutateNestedProp(directive, updatedStateData.keyPath, updatedStateData.newValue); - if (ngDebugApiIsSupported(ng, 'getOwningComponent')) { - ng.applyChanges?.(ng.getOwningComponent(directive)!); - } - return; - } - if (node.component) { - const comp = node.component.instance; - mutateNestedProp(comp, updatedStateData.keyPath, updatedStateData.newValue); - ng.applyChanges?.(comp); - return; - } -}; - -export function logValue(valueInfo: { - directiveId: DirectivePosition; - keyPath: string[] | null; -}): void { - const node = queryDirectiveForest(valueInfo.directiveId.element, buildDirectiveForest()); - if (!node) { - log.warn( - 'Could not log the value of component', - valueInfo, - 'because the directive was not found', - ); - return; - } - - if (node.directives && valueInfo.directiveId.directive !== undefined) { - const directiveInstance = node.directives[valueInfo.directiveId.directive].instance; - if (valueInfo.keyPath === null) { - logSignalToConsole(directiveInstance); - return; - } - - const value = valueInfo.keyPath.reduce((obj, key) => obj && obj[key], directiveInstance); - logSignalToConsole(value); - return; - } - if (node.component) { - const compInstance = node.component.instance; - if (valueInfo.keyPath === null) { - logSignalToConsole(compInstance); - return; - } - const value = valueInfo.keyPath.reduce((obj, key) => obj && obj[key], compInstance); - logSignalToConsole(value); - return; - } -} - -function logSignalToConsole(value: unknown) { - // tslint:disable-next-line:no-console - console.log(unwrapSignal(value)); -} - -export function serializeResolutionPath(resolutionPath: Injector[]): SerializedInjector[] { - const serializedResolutionPath: SerializedInjector[] = []; - - for (const injector of resolutionPath) { - let serializedInjectorWithId: SerializedInjector | null = null; - - if (isElementInjector(injector)) { - serializedInjectorWithId = serializeElementInjectorWithId(injector); - } else { - serializedInjectorWithId = serializeEnvironmentInjectorWithId(injector); - } - - if (serializedInjectorWithId === null) { - continue; - } - - serializedResolutionPath.push(serializedInjectorWithId); - } - - return serializedResolutionPath; -} - -export function findDirectiveAndHost(el: Node | undefined): { - directive: any; - host: Element | null; -} { - const ng = ngDebugClient(); - if (!el) { - return {directive: null, host: null}; - } - while (el) { - if (el instanceof Element) { - const component = ng.getComponent?.(el); - if (component) { - return {directive: component, host: el}; - } - const directive = ng.getDirectives?.(el)?.[0]; - if (directive) { - return {directive, host: el}; - } - } - if (!el.parentElement) { - break; - } - el = el.parentElement; - } - return {directive: null, host: null}; -} - -// Note(hawkgs): Duplicate in directive-forest due ot cyclic dependency. -export function getDirectiveName(dir: Type | undefined | null): string { - return dir ? dir.constructor.name : 'unknown'; -} diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/directive-forest.spec.ts b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/directive-forest.spec.ts new file mode 100644 index 00000000000..a30a135c675 --- /dev/null +++ b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/directive-forest.spec.ts @@ -0,0 +1,102 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import {ɵExternalCoreGlobalUtils} from '@angular/core'; +import {getRootElements} from '.'; + +type Ng = ɵExternalCoreGlobalUtils; +const NG_VERSION = 'ng-version'; +const VERSION = '0.0.0-PLACEHOLDER'; + +function setNgVersion(element: Element) { + element.setAttribute(NG_VERSION, VERSION); +} + +function createRoot() { + const root = document.createElement('div'); + setNgVersion(root); + return root; +} + +describe('directive-forest', () => { + afterEach(() => { + delete (globalThis as any).ng; + }); + + describe('getRootElements', () => { + beforeEach(() => { + const ng: Partial = { + getComponent: jasmine.createSpy('getComponent').and.callFake((element: HTMLElement) => { + // Will treat only `ng-*` elements as Angular components. + if (element.tagName.toLowerCase().startsWith('ng-')) { + return element; + } + return null; + }), + }; + (window as any).ng = ng; + }); + + afterEach(() => { + document.body.replaceChildren(); + document.body.removeAttribute(NG_VERSION); + delete (window as any).ng; + }); + + it('should return root element', () => { + const rootElement = createRoot(); + const childElement = createRoot(); + + rootElement.appendChild(childElement); + document.body.appendChild(rootElement); + + const roots = getRootElements(); + + expect(roots.length).toEqual(1); + expect(roots.pop()).toEqual(rootElement); + }); + + it('should return multiple sibling roots', () => { + const firstRoot = createRoot(); + const secondRoot = createRoot(); + + document.body.appendChild(firstRoot); + document.body.appendChild(secondRoot); + + const roots = getRootElements(); + + expect(roots.length).toEqual(2); + expect(roots).toContain(firstRoot); + expect(roots).toContain(secondRoot); + }); + + it('should only return document.body when document.body is the root', () => { + setNgVersion(document.body); + const child1 = createRoot(); + document.body.appendChild(child1); + const roots = getRootElements(); + expect(roots.length).toEqual(1); + expect(roots).toContain(document.body); + }); + + it('should return all root elements with all non-application root components', () => { + const rootElement = createRoot(); + const childElement = createRoot(); + const nonAppRootCmp = document.createElement('ng-cmp'); + + rootElement.appendChild(childElement); + document.body.appendChild(rootElement); + document.body.appendChild(nonAppRootCmp); + + const roots = getRootElements(); + + expect(roots.length).toEqual(2); + expect(roots).toEqual([rootElement, nonAppRootCmp]); + }); + }); +}); diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/directive-state/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/directive-state/BUILD.bazel new file mode 100644 index 00000000000..34aad3124da --- /dev/null +++ b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/directive-state/BUILD.bazel @@ -0,0 +1,21 @@ +load("//devtools/tools:defaults.bzl", "ts_project") + +package(default_visibility = ["//devtools:__subpackages__"]) + +ts_project( + name = "directive-state", + srcs = ["directive-state.ts"], + deps = [ + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest:core-enums", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/property-mutation", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils:directive", + "//devtools/projects/ng-devtools-backend/src/lib/injector-tree", + "//devtools/projects/ng-devtools-backend/src/lib/shared:interfaces", + "//devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api", + "//devtools/projects/ng-devtools-backend/src/lib/shared/state-serializer", + "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:general", + "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:log", + "//devtools/projects/protocol", + ], +) diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/directive-state/directive-state.ts b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/directive-state/directive-state.ts new file mode 100644 index 00000000000..65a5190a98d --- /dev/null +++ b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/directive-state/directive-state.ts @@ -0,0 +1,172 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { + ComponentExplorerViewQuery, + DirectivePosition, + DirectivesProperties, + PropertyQueryTypes, + UpdatedStateData, +} from '../../../../../protocol'; +import { + getDependenciesForDirective, + getInjectorFromElementNode, + getInjectorProviders, + getInjectorResolutionPath, +} from '../../injector-tree/injector-tree'; +import { + ComponentInstanceType, + ComponentTreeNode, + DirectiveInstanceType, +} from '../../shared/interfaces'; +import { + ngDebugApiIsSupported, + ngDebugClient, + ngDebugDependencyInjectionApiIsSupported, +} from '../../shared/ng-debug-api/ng-debug-api'; +import { + deeplySerializeSelectedProperties, + serializeDirectiveState, +} from '../../shared/state-serializer/state-serializer'; +import {unwrapSignal} from '../../shared/utils/general'; +import {log} from '../../shared/utils/log'; +import {buildDirectiveForest, queryDirectiveForest} from '..'; +import {Framework} from '../core-enums'; +import {mutateNestedProp} from '../property-mutation/property-mutation'; +import {getDirectiveMetadata} from '../utils/directive'; + +export function getLatestDirectiveState( + query: ComponentExplorerViewQuery, + directiveForest?: ComponentTreeNode[], +): {directiveProperties: DirectivesProperties} | undefined { + // if a directive forest is passed in we don't have to build the forest again. + directiveForest = directiveForest ?? buildDirectiveForest(); + + const node = queryDirectiveForest(query.selectedElement, directiveForest); + if (!node) { + return; + } + + const directiveProperties: DirectivesProperties = {}; + + const injector = getInjectorFromElementNode(node.nativeElement!); + + const injectors = injector ? getInjectorResolutionPath(injector) : []; + const resolutionPathWithProviders = !ngDebugDependencyInjectionApiIsSupported() + ? [] + : injectors.map((injector) => ({ + injector, + providers: getInjectorProviders(injector), + })); + const populateResultSet = (dir: DirectiveInstanceType | ComponentInstanceType) => { + const {instance, name} = dir; + const metadata = getDirectiveMetadata(instance); + if (injector && metadata.framework === Framework.Angular) { + metadata.dependencies = getDependenciesForDirective( + injector, + resolutionPathWithProviders, + instance.constructor, + ); + } + + if (query.propertyQuery.type === PropertyQueryTypes.All) { + directiveProperties[dir.name] = { + props: serializeDirectiveState(instance), + metadata, + }; + } + + if (query.propertyQuery.type === PropertyQueryTypes.Specified) { + directiveProperties[name] = { + props: deeplySerializeSelectedProperties( + instance, + query.propertyQuery.properties[name] || [], + ), + metadata, + }; + } + }; + + node.directives?.forEach((dir) => populateResultSet(dir)); + if (node.component) { + populateResultSet(node.component); + } + + return { + directiveProperties, + }; +} + +export function updateDirectiveState(updatedStateData: UpdatedStateData): void { + const ng = ngDebugClient(); + const node = queryDirectiveForest(updatedStateData.directiveId.element, buildDirectiveForest()); + if (!node) { + log.warn( + 'Could not update the state of component', + updatedStateData, + 'because the component was not found', + ); + return; + } + if (node.directives && updatedStateData.directiveId.directive !== undefined) { + const directive = node.directives[updatedStateData.directiveId.directive].instance; + mutateNestedProp(directive, updatedStateData.keyPath, updatedStateData.newValue); + if (ngDebugApiIsSupported(ng, 'getOwningComponent')) { + ng.applyChanges?.(ng.getOwningComponent(directive)!); + } + return; + } + if (node.component) { + const comp = node.component.instance; + mutateNestedProp(comp, updatedStateData.keyPath, updatedStateData.newValue); + ng.applyChanges?.(comp); + return; + } +} + +export function logDirectiveValue(valueInfo: { + directiveId: DirectivePosition; + keyPath: string[] | null; +}): void { + const node = queryDirectiveForest(valueInfo.directiveId.element, buildDirectiveForest()); + if (!node) { + log.warn( + 'Could not log the value of component', + valueInfo, + 'because the directive was not found', + ); + return; + } + + if (node.directives && valueInfo.directiveId.directive !== undefined) { + const directiveInstance = node.directives[valueInfo.directiveId.directive].instance; + if (valueInfo.keyPath === null) { + logSignalToConsole(directiveInstance); + return; + } + + const value = valueInfo.keyPath.reduce((obj, key) => obj && obj[key], directiveInstance); + logSignalToConsole(value); + return; + } + if (node.component) { + const compInstance = node.component.instance; + if (valueInfo.keyPath === null) { + logSignalToConsole(compInstance); + return; + } + const value = valueInfo.keyPath.reduce((obj, key) => obj && obj[key], compInstance); + logSignalToConsole(value); + return; + } +} + +function logSignalToConsole(value: unknown) { + // tslint:disable-next-line:no-console + console.log(unwrapSignal(value)); +} diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/identity-tracker/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/identity-tracker/BUILD.bazel index 0a3211eb368..80d32379fce 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/identity-tracker/BUILD.bazel +++ b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/identity-tracker/BUILD.bazel @@ -8,7 +8,7 @@ ts_project( "identity-tracker.ts", ], deps = [ - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest", "//devtools/projects/ng-devtools-backend/src/lib/shared:interfaces", "//devtools/projects/protocol", ], diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/identity-tracker/identity-tracker.ts b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/identity-tracker/identity-tracker.ts index f90e78f2ff1..cca34f6dd15 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/identity-tracker/identity-tracker.ts +++ b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/identity-tracker/identity-tracker.ts @@ -6,9 +6,9 @@ * found in the LICENSE file at https://angular.dev/license */ +import {buildDirectiveForest} from '..'; import {DevToolsNode, ElementPosition} from '../../../../../protocol'; -import {buildDirectiveForest} from '../component-tree/component-tree'; import { ComponentInstance, ComponentInstanceType, diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/index.ts b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/index.ts index 2103c70b9c2..4988a5787be 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/index.ts +++ b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/index.ts @@ -6,9 +6,171 @@ * found in the LICENSE file at https://angular.dev/license */ +import {ElementPosition} from '../../../../protocol'; +import {ComponentTreeNode} from '../shared/interfaces'; +import {ngDebugClient} from '../shared/ng-debug-api/ng-debug-api'; import {selectTreeStrategy} from './tree-strategies'; +import {getAppRoots} from './utils/app-roots'; -export const buildDirectiveForestWithStrategy = (elements: Element[]) => { +/** Gets the all the root components in the Dom, including those outside the application root */ +export function getRootElements(): Element[] { + if (!ngDebugClient().getComponent) { + // If the ngDebugClient does not support getComponent, we cannot proceed. + return []; + } + + const roots = getAppRoots(); + const rootSet = new Set(roots); + + // Traverse the DOM tree for other non application root Angular components. + // Pass in the existing roots to inform the traversal that we can skip those paths. + discoverNonApplicationRootComponents(document.body, rootSet); + + return [...rootSet]; +} + +export function buildDirectiveForest(): ComponentTreeNode[] { + const ng = ngDebugClient(); + if ((ng as any).getComponentForest) { + const forest: ComponentTreeNode[] = (ng as any).getComponentForest(); + const frontier = [...forest]; + while (frontier.length) { + const node = frontier.pop()!; + const rawNode = node as any; + node.tagName ??= rawNode.element ?? rawNode.nativeElement?.nodeName.toLowerCase() ?? ''; + node.component!.isElement ??= false; + for (const child of node.children) { + frontier.push(child); + } + } + return forest; + } + return buildDirectiveForestWithStrategy(getRootElements()); +} + +// Based on an ElementID we return a specific component node. +// If we can't find any, we return null. +export function queryDirectiveForest( + position: ElementPosition, + forest: ComponentTreeNode[], +): ComponentTreeNode | null { + if (!position.length) { + return null; + } + let node: null | ComponentTreeNode = null; + for (const i of position) { + node = forest[i]; + if (!node) { + return null; + } + forest = node.children; + } + if (node?.controlFlowBlock) { + return null; + } + return node; +} + +export function findNodeInForest( + position: ElementPosition, + forest: ComponentTreeNode[], +): Element | null { + const foundComponent: ComponentTreeNode | null = queryDirectiveForest(position, forest); + const nativeElement = foundComponent?.nativeElement; + return nativeElement instanceof Element ? nativeElement : null; +} + +export function findNodeFromSerializedPosition( + serializedPosition: string, +): ComponentTreeNode | null { + const position: number[] = JSON.parse(serializedPosition); + return queryDirectiveForest(position, buildDirectiveForest()); +} + +/** + * Warning: This function mutates the `roots` arg! + * + * Recursively traverse the DOM tree to find all Angular component root elements. + * + * This function starts from the given element and traverses its children. + * When it finds an Angular component, it adds that element to the `roots` set. + * + * If we discover an angular component that we've already added to the `roots` set, + * we skip traversing its children. This is to ensure that we only collect unique root elements. + * + * + * Example: + * + * Lets say we have the following DOM structure: + * + * ```html + * + * ... + * ... + * + * + * ... + * + * + *
Not an angular component
+ * + * + * ``` + * + * In this case, `app-root-1` and `app-root-2` are the root elements of Angular components. + * The `mat-dialog` is a non application root Angular component. + * + * We can discover the roots by searching for ng-version. This gives us a set of paths that we can skip traversing. + * + * ```ts + * const rootSet = new Set(getAppRoots()); + * console.log(rootSet); + * // Set(, ) + * discoverNonApplicationRootComponents(document.body, rootSet); + * console.log(rootSet); + * // Set(, , ) + * ``` + * + * ```md + * + * traversing document.body.children: + * - child: + * - Since we have this already in the `roots` set, we skip traversing its children. + * - child: + * - Since we have this already in the `roots` set, we skip traversing its children. + * - child: + * - Since this is not in the `roots` set, we check if it is an Angular component. + * - Since it is, we add it to the `roots` set and break the loop. + * - child:
+ * - Since this is not an Angular component, we traverse its children to see if we can find any Angular components. + * + * ``` + * + * @param element The current DOM element being traversed. + * @param roots A set of root elements found during the traversal. + */ +function discoverNonApplicationRootComponents(element: Element, roots: Set): void { + if (roots.has(element)) { + return; + } + const children = Array.from(element.children); + for (const child of children) { + if (roots.has(child)) { + continue; + } + + const ng = ngDebugClient(); + if (ng.getComponent && ng.getComponent(child)) { + roots.add(child); + // If the child is an Angular component, we can skip traversing its children. + continue; + } + + discoverNonApplicationRootComponents(child, roots); + } +} + +function buildDirectiveForestWithStrategy(elements: Element[]) { if (!elements || !elements.length) { return []; } @@ -24,4 +186,4 @@ export const buildDirectiveForestWithStrategy = (elements: Element[]) => { return strategy.build(element, i++); }); -}; +} diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/tree-strategies/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/tree-strategies/BUILD.bazel index 9dcaf7c2f4a..dd03887f121 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/tree-strategies/BUILD.bazel +++ b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/tree-strategies/BUILD.bazel @@ -17,6 +17,7 @@ ts_project( "//devtools/projects/ng-devtools-backend/src/lib:version", "//devtools/projects/ng-devtools-backend/src/lib/config", "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils:control-flow", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils:directive", "//devtools/projects/ng-devtools-backend/src/lib/shared:interfaces", "//devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api", "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:error", diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/tree-strategies/ltree.ts b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/tree-strategies/ltree.ts index b7b07549f83..292fd3bb801 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/tree-strategies/ltree.ts +++ b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/tree-strategies/ltree.ts @@ -8,7 +8,6 @@ import semver from 'semver'; -import {Type} from '@angular/core'; import { ComponentInstanceType, ComponentTreeNode, @@ -16,6 +15,7 @@ import { } from '../../shared/interfaces'; import {isCustomElement} from '../../shared/utils/general'; import {VERSION} from '../../version'; +import {getDirectiveName} from '../utils/directive'; let HEADER_OFFSET = 19; @@ -161,8 +161,3 @@ export class LTreeStrategy { return this.extract(rootLView); } } - -// Note(hawkgs): Duplicate due to cyclic dependency. -function getDirectiveName(dir: Type | undefined | null): string { - return dir ? dir.constructor.name : 'unknown'; -} diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/BUILD.bazel index 1eeb3010107..9c3ba4e8f9e 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/BUILD.bazel +++ b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/BUILD.bazel @@ -1,4 +1,4 @@ -load("//devtools/tools:defaults.bzl", "ts_project") +load("//devtools/tools:defaults.bzl", "ts_project", "ts_test_library", "zoneless_web_test_suite") package(default_visibility = ["//devtools:__subpackages__"]) @@ -14,3 +14,48 @@ ts_project( "//devtools/projects/protocol", ], ) + +ts_project( + name = "app-roots", + srcs = [ + "app-roots.ts", + ], +) + +ts_project( + name = "directive", + srcs = [ + "directive.ts", + ], + deps = [ + "//:node_modules/@angular/core", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest:core-enums", + "//devtools/projects/ng-devtools-backend/src/lib/shared:interfaces", + "//devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api", + "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:error", + "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:log", + "//devtools/projects/protocol", + ], +) + +ts_test_library( + name = "test_lib", + srcs = [ + "app-roots.spec.ts", + "directive.spec.ts", + ], + deps = [ + ":app-roots", + ":directive", + "//:node_modules/@angular/core", + "//:node_modules/jasmine", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest:core-enums", + ], +) + +zoneless_web_test_suite( + name = "test", + deps = [ + ":test_lib", + ], +) diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/get-roots.spec.ts b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/app-roots.spec.ts similarity index 93% rename from devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/get-roots.spec.ts rename to devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/app-roots.spec.ts index 251e241bc5d..9052396e84c 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/get-roots.spec.ts +++ b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/app-roots.spec.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.dev/license */ -import {getAppRoots} from './get-roots'; +import {getAppRoots} from './app-roots'; function createRoot() { const root = document.createElement('div'); @@ -14,7 +14,7 @@ function createRoot() { return root; } -describe('getRoots', () => { +describe('getAppRoots', () => { afterEach(() => { document.body.replaceChildren(); }); diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/get-roots.ts b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/app-roots.ts similarity index 100% rename from devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree/get-roots.ts rename to devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/app-roots.ts diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/directive.spec.ts b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/directive.spec.ts new file mode 100644 index 00000000000..957a1ed508d --- /dev/null +++ b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/directive.spec.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import {ɵExternalCoreGlobalUtils} from '@angular/core'; +import {getDirectiveCdStrategy} from './directive'; +import {ChangeDetectionStrategy, Framework} from '../core-enums'; + +type Ng = ɵExternalCoreGlobalUtils; + +describe('directive utils', () => { + afterEach(() => { + delete (globalThis as any).ng; + }); + + describe('getDirectiveCdStrategy', () => { + it('returns change detection strategy when passed valid component', () => { + const ng: Partial = { + getDirectiveMetadata: jasmine.createSpy('getDirectiveMetadata').and.returnValue({ + framework: Framework.Angular, + changeDetection: ChangeDetectionStrategy.OnPush, + } as any), + }; + (globalThis as any).ng = ng; + + const result = getDirectiveCdStrategy({ + instance: {}, + name: 'Foo', + isElement: false, + }); + expect(result).toBe('ng-on-push'); + }); + }); +}); diff --git a/devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/directive.ts b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/directive.ts new file mode 100644 index 00000000000..944a2a7da08 --- /dev/null +++ b/devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils/directive.ts @@ -0,0 +1,174 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { + ɵAcxComponentDebugMetadata as AcxComponentDebugMetadata, + ɵAngularComponentDebugMetadata as AngularComponentDebugMetadata, + Type, +} from '@angular/core'; +import {ChangeDetection, DirectiveMetadata} from '../../../../../protocol'; +import {ComponentInstanceType} from '../../shared/interfaces'; +import {ngDebugApiIsSupported, ngDebugClient} from '../../shared/ng-debug-api/ng-debug-api'; +import {AngularDevtoolsError} from '../../shared/utils/error'; +import {log} from '../../shared/utils/log'; +import {AcxChangeDetectionStrategy, ChangeDetectionStrategy, Framework} from '../core-enums'; + +const enum DirectiveMetadataKey { + INPUTS = 'inputs', + OUTPUTS = 'outputs', + ENCAPSULATION = 'encapsulation', + CHANGE_DETECTION = 'changeDetection', +} + +// Gets directive metadata. For newer versions of Angular (v12+) it uses +// the global `getDirectiveMetadata`. For prior versions of the framework +// the method directly interacts with the directive/component definition. +export function getDirectiveMetadata(dir: any): DirectiveMetadata { + const getMetadata = ngDebugClient().getDirectiveMetadata; + const metadata = dir ? getMetadata?.(dir) : null; + if (metadata) { + const {framework} = metadata; + switch (framework) { + case undefined: // Back compat, older Angular versions did not set `framework`. + case Framework.Angular: { + const meta = metadata as typeof metadata & Partial; + return { + framework: Framework.Angular, + name: meta.name, + inputs: meta.inputs, + outputs: meta.outputs, + encapsulation: meta.encapsulation, + changeDetection: meta.changeDetection, + }; + } + case Framework.ACX: { + const meta = metadata as typeof metadata & Partial; + return { + framework: Framework.ACX, + name: meta.name, + inputs: meta.inputs, + outputs: meta.outputs, + encapsulation: meta.encapsulation, + changeDetection: meta.changeDetection, + }; + } + case Framework.Wiz: { + return { + framework: Framework.Wiz, + name: metadata.name, + props: metadata.props, + }; + } + default: { + throw new AngularDevtoolsError(`Unknown framework: "${framework}".`); + } + } + } + + // Used in older Angular versions, prior to the introduction of `getDirectiveMetadata`. + const safelyGrabMetadata = (key: DirectiveMetadataKey) => { + try { + return dir.constructor.ɵcmp ? dir.constructor.ɵcmp[key] : dir.constructor.ɵdir[key]; + } catch { + log.warn(`Could not find metadata for key: ${key} in directive:`, dir); + return undefined; + } + }; + + return { + framework: Framework.Angular, + inputs: safelyGrabMetadata(DirectiveMetadataKey.INPUTS), + outputs: safelyGrabMetadata(DirectiveMetadataKey.OUTPUTS), + encapsulation: safelyGrabMetadata(DirectiveMetadataKey.ENCAPSULATION), + changeDetection: safelyGrabMetadata(DirectiveMetadataKey.CHANGE_DETECTION), + }; +} + +export function getDirectiveCdStrategy(dir: ComponentInstanceType): ChangeDetection | undefined { + const metadata = getDirectiveMetadata(dir.instance); + + switch (metadata.framework) { + case Framework.Angular: + switch (metadata.changeDetection) { + case ChangeDetectionStrategy.OnPush: + return 'ng-on-push'; + case ChangeDetectionStrategy.Eager: + return 'ng-eager'; + } + + case Framework.ACX: + switch (metadata.changeDetection) { + case AcxChangeDetectionStrategy.Default: + return 'acx-default'; + case AcxChangeDetectionStrategy.OnPush: + return 'acx-on-push'; + } + + case Framework.Wiz: + return undefined; + + default: + throw new AngularDevtoolsError( + `Unknown framework: "${(metadata as {framework: string}).framework}".`, + ); + } +} + +export function findDirectiveAndHost(el: Node | undefined): { + directive: any; + host: Element | null; +} { + const ng = ngDebugClient(); + if (!el) { + return {directive: null, host: null}; + } + while (el) { + if (el instanceof Element) { + const component = ng.getComponent?.(el); + if (component) { + return {directive: component, host: el}; + } + const directive = ng.getDirectives?.(el)?.[0]; + if (directive) { + return {directive, host: el}; + } + } + if (!el.parentElement) { + break; + } + el = el.parentElement; + } + return {directive: null, host: null}; +} + +export function getDirectiveName(dir: Type | undefined | null): string { + return dir ? dir.constructor.name : 'unknown'; +} + +export function elementToDirectiveNames(element: HTMLElement): string[] { + const {component, directives} = getDirectivesFromElement(element); + return [component, ...directives] + .map((dir) => dir?.constructor?.name ?? '') + .filter((dir) => !!dir); +} + +export function getDirectivesFromElement(element: HTMLElement): { + component: unknown | null; + directives: unknown[]; +} { + const ng = ngDebugClient(); + let component = null; + if (element instanceof Element && ngDebugApiIsSupported(ng, 'getComponent')) { + component = ng.getComponent(element); + } + + return { + component, + directives: ngDebugClient().getDirectives?.(element) ?? [], + }; +} diff --git a/devtools/projects/ng-devtools-backend/src/lib/injector-tree/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/lib/injector-tree/BUILD.bazel new file mode 100644 index 00000000000..4623fa4cab2 --- /dev/null +++ b/devtools/projects/ng-devtools-backend/src/lib/injector-tree/BUILD.bazel @@ -0,0 +1,33 @@ +load("//devtools/tools:defaults.bzl", "ts_project", "ts_test_library", "zoneless_web_test_suite") + +package(default_visibility = ["//devtools:__subpackages__"]) + +ts_project( + name = "injector-tree", + srcs = [ + "injector-tree.ts", + ], + deps = [ + "//:node_modules/@angular/core", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils:directive", + "//devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api", + "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:error", + "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:log", + "//devtools/projects/protocol", + ], +) + +ts_test_library( + name = "test_lib", + srcs = ["injector-tree.spec.ts"], + deps = [ + ":injector-tree", + "//:node_modules/@angular/core", + "//:node_modules/jasmine", + ], +) + +zoneless_web_test_suite( + name = "test", + deps = [":test_lib"], +) diff --git a/devtools/projects/ng-devtools-backend/src/lib/injector-tree/injector-tree.spec.ts b/devtools/projects/ng-devtools-backend/src/lib/injector-tree/injector-tree.spec.ts new file mode 100644 index 00000000000..528d8d0dc35 --- /dev/null +++ b/devtools/projects/ng-devtools-backend/src/lib/injector-tree/injector-tree.spec.ts @@ -0,0 +1,98 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { + Injector, + ɵExternalCoreGlobalUtils, + ɵProviderRecord as ProviderRecord, + InjectionToken, +} from '@angular/core'; +import {getInjectorFromElementNode, serializeProviderRecord} from './injector-tree'; + +type Ng = ɵExternalCoreGlobalUtils; + +describe('injector-tree', () => { + afterEach(() => { + delete (globalThis as any).ng; + }); + + describe('getInjectorFromElementNode', () => { + it('returns injector', () => { + const injector = Injector.create({ + providers: [], + }); + + const ng: Partial = { + getInjector: jasmine.createSpy('getInjector').and.returnValue(injector), + }; + (globalThis as any).ng = ng; + + const el = document.createElement('div'); + expect(getInjectorFromElementNode(el)).toBe(injector); + expect(ng.getInjector).toHaveBeenCalledOnceWith(el); + }); + + it('returns `null` when `getInjector` is not supported', () => { + (globalThis as any).ng = {}; + + const el = document.createElement('div'); + expect(getInjectorFromElementNode(el)).toBeNull(); + }); + }); + + describe('serializeProviderRecord', () => { + it('should return "internal" type for internal tokens', () => { + const internalTokenNames = [ + 'ElementRef', + 'Renderer2', + 'ViewContainerRef', + 'DestroyRef', + 'ChangeDetectorRef', + 'Injector', + ]; + + internalTokenNames.forEach((tokenName, index) => { + const token = () => {}; + Object.defineProperty(token, 'name', {value: tokenName}); + const providerRecord: any = { + provider: () => {}, + token, + isViewProvider: false, + }; + const result = serializeProviderRecord(providerRecord, index); + expect(result.type).toBe('internal'); + expect(result.token).toBe(tokenName); + }); + }); + + it('should return "type" for non-internal function providers', () => { + const token = () => {}; + Object.defineProperty(token, 'name', {value: 'MyCustomService'}); + const providerRecord: any = { + provider: () => {}, + token, + isViewProvider: false, + }; + const result = serializeProviderRecord(providerRecord, 0); + expect(result.type).toBe('type'); + expect(result.token).toBe('MyCustomService'); + }); + + it('should handle injection tokens', () => { + const result = serializeProviderRecord( + { + token: new InjectionToken('FOO'), + isViewProvider: false, + } as ProviderRecord, + 0, + ); + + expect(result.token).toBe('InjectionToken (FOO)'); + }); + }); +}); diff --git a/devtools/projects/ng-devtools-backend/src/lib/injector-tree/injector-tree.ts b/devtools/projects/ng-devtools-backend/src/lib/injector-tree/injector-tree.ts new file mode 100644 index 00000000000..130ec40dfc9 --- /dev/null +++ b/devtools/projects/ng-devtools-backend/src/lib/injector-tree/injector-tree.ts @@ -0,0 +1,378 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { + ClassProvider, + ExistingProvider, + FactoryProvider, + InjectOptions, + InjectionToken, + Injector, + ɵProviderRecord as ProviderRecord, + Type, + ValueProvider, +} from '@angular/core'; +import { + SerializedInjectedService, + SerializedInjector, + SerializedProviderRecord, +} from '../../../../protocol'; +import {ngDebugApiIsSupported, ngDebugClient} from '../shared/ng-debug-api/ng-debug-api'; +import {log} from '../shared/utils/log'; +import {AngularDevtoolsError} from '../shared/utils/error'; +import {elementToDirectiveNames} from '../directive-forest/utils/directive'; + +const INTERNAL_TOKENS = [ + 'ElementRef', + 'Renderer2', + 'ViewContainerRef', + 'DestroyRef', + 'ChangeDetectorRef', + 'Injector', +]; + +export const injectorToId = new WeakMap(); +export const nodeInjectorToResolutionPath = new WeakMap(); +export const idToInjector = new Map>(); +const injectorFinalizer = new FinalizationRegistry((id) => { + idToInjector.delete(id); +}); +let injectorId = 0; + +export function getInjectorId() { + return `${injectorId++}`; +} + +export function getInjectorMetadata( + injector: Injector, +): ReturnType['ɵgetInjectorMetadata']>> { + return ngDebugClient().ɵgetInjectorMetadata?.(injector) ?? null; +} + +export function getInjectorResolutionPath(injector: Injector): Injector[] { + const ng = ngDebugClient(); + if (!ngDebugApiIsSupported(ng, 'ɵgetInjectorResolutionPath')) { + return []; + } + + return ng.ɵgetInjectorResolutionPath(injector) ?? []; +} + +export function getInjectorFromElementNode(element: Node): Injector | null { + try { + return ngDebugClient().getInjector?.(element) ?? null; + } catch { + return null; + } +} + +export function getInjectorProviders(injector: Injector) { + if (isNullInjector(injector)) { + return []; + } + + return ngDebugClient().ɵgetInjectorProviders!(injector); +} + +export function getDependenciesForDirective( + injector: Injector, + resolutionPath: {injector: Injector; providers: ProviderRecord[]}[], + directive: any, +): SerializedInjectedService[] { + const ng = ngDebugClient(); + if (!ngDebugApiIsSupported(ng, 'ɵgetDependenciesFromInjectable')) { + return []; + } + + let dependencies = ng.ɵgetDependenciesFromInjectable(injector, directive)?.dependencies ?? []; + const uniqueServices = new Set(); + const serializedInjectedServices: SerializedInjectedService[] = []; + + let position = 0; + for (const dependency of dependencies) { + const providedIn = dependency.providedIn; + const foundInjectorIndex = resolutionPath.findIndex((node) => node.injector === providedIn); + + if (foundInjectorIndex === -1) { + position++; + continue; + } + + const providers = resolutionPath[foundInjectorIndex].providers; + const foundProvider = providers.find((provider) => provider.token === dependency.token); + + // the dependency resolution path is + // the path from the root injector to the injector that provided the dependency (1) + // + + // the import path from the providing injector to the feature module that provided the + // dependency (2) + const dependencyResolutionPath: SerializedInjector[] = [ + // (1) + ...resolutionPath + .slice(0, foundInjectorIndex + 1) + .map((node) => serializeInjectorWithId(node.injector)!), + + // (2) + // We slice the import path to remove the first element because this is the same + // injector as the last injector in the resolution path. + ...(foundProvider?.importPath ?? []).slice(1).map((node): SerializedInjector => { + return { + type: 'imported-module', + name: valueToLabel(node), + id: getInjectorId(), + }; + }), + ]; + + let flags = dependency.flags as InjectOptions; + let flagToken = ''; + if (flags !== undefined) { + if (typeof flags === 'number') { + flags = { + optional: !!(flags & 8), + skipSelf: !!(flags & 4), + self: !!(flags & 2), + host: !!(flags & 1), + }; + } + flagToken = (['optional', 'skipSelf', 'self', 'host'] as (keyof InjectOptions)[]) + .filter((key) => flags[key]) + .join('-'); + } + + const serviceKey = `${dependency.token}-${flagToken}`; + if (!uniqueServices.has(serviceKey)) { + uniqueServices.add(serviceKey); + + const service = { + token: valueToLabel(dependency.token), + value: valueToLabel(dependency.value), + flags, + position: [position], + resolutionPath: dependencyResolutionPath, + }; + + serializedInjectedServices.push(service); + } + + position++; + } + + return serializedInjectedServices; +} + +export function serializeInjector(injector: Injector): Omit | null { + const metadata = getInjectorMetadata(injector); + + if (metadata === null) { + log.error('Could not serialize injector.', injector); + return null; + } + + const providers = getInjectorProviders(injector).length; + + if (metadata.type === 'null') { + return {type: 'null', name: 'Null Injector', providers: 0}; + } + + if (metadata.type === 'element') { + const source = metadata.source as HTMLElement; + const name = stripUnderscore(elementToDirectiveNames(source)[0]); + + return {type: 'element', name, providers}; + } + + if (metadata.type === 'environment') { + if ((injector as any).scopes instanceof Set) { + if ((injector as any).scopes.has('platform')) { + return {type: 'environment', name: 'Platform', providers}; + } + + if ((injector as any).scopes.has('root')) { + return {type: 'environment', name: 'Root', providers}; + } + } + + return {type: 'environment', name: stripUnderscore(metadata.source ?? ''), providers}; + } + + log.error('Could not serialize injector.', injector); + return null; +} + +export function serializeProviderRecord( + providerRecord: ProviderRecord, + index: number, + hasImportPath = false, +): SerializedProviderRecord { + let type: 'type' | 'class' | 'value' | 'factory' | 'existing' | 'internal' = 'type'; + let multi = false; + + if (typeof providerRecord.provider === 'object') { + if ((providerRecord.provider as ClassProvider).useClass !== undefined) { + type = 'class'; + } else if ((providerRecord.provider as ValueProvider).useValue !== undefined) { + type = 'value'; + } else if ((providerRecord.provider as FactoryProvider).useFactory !== undefined) { + type = 'factory'; + } else if ((providerRecord.provider as ExistingProvider).useExisting !== undefined) { + type = 'existing'; + } + + if (providerRecord.provider.multi !== undefined) { + multi = providerRecord.provider.multi; + } + } else if (typeof providerRecord.provider === 'function') { + if (INTERNAL_TOKENS.includes((providerRecord.token as Type).name)) { + type = 'internal'; + } + } + + const serializedProvider: { + token: string; + type: typeof type; + multi: boolean; + isViewProvider: boolean; + index: number; + importPath?: string[]; + } = { + token: valueToLabel(providerRecord.token), + type, + multi, + isViewProvider: providerRecord.isViewProvider, + index, + }; + + if (hasImportPath) { + serializedProvider['importPath'] = (providerRecord.importPath ?? []).map((injector) => + valueToLabel(injector), + ); + } + + return serializedProvider; +} + +export function getElementInjectorElement(elementInjector: Injector): HTMLElement { + if (!isElementInjector(elementInjector)) { + throw new AngularDevtoolsError('Injector is not an element injector'); + } + + return getInjectorMetadata(elementInjector)!.source as HTMLElement; +} + +export function isElementInjector(injector: Injector) { + const metadata = getInjectorMetadata(injector); + return metadata !== null && metadata.type === 'element'; +} + +export function serializeResolutionPath(resolutionPath: Injector[]): SerializedInjector[] { + const serializedResolutionPath: SerializedInjector[] = []; + + for (const injector of resolutionPath) { + let serializedInjectorWithId: SerializedInjector | null = null; + + if (isElementInjector(injector)) { + serializedInjectorWithId = serializeElementInjectorWithId(injector); + } else { + serializedInjectorWithId = serializeEnvironmentInjectorWithId(injector); + } + + if (serializedInjectorWithId === null) { + continue; + } + + serializedResolutionPath.push(serializedInjectorWithId); + } + + return serializedResolutionPath; +} + +function getOrCreateInjectorId(key: Injector | HTMLElement, injector: Injector): string { + if (!injectorToId.has(key)) { + const newId = getInjectorId(); + injectorToId.set(key, newId); + idToInjector.set(newId, new WeakRef(injector)); + injectorFinalizer.register(injector, newId); + } + return injectorToId.get(key)!; +} + +function serializeElementInjectorWithId(injector: Injector): SerializedInjector | null { + const element = getElementInjectorElement(injector); + const id = getOrCreateInjectorId(element, injector); + + const serializedInjector = serializeInjector(injector); + if (serializedInjector === null) { + return null; + } + + return {id, ...serializedInjector}; +} + +function serializeInjectorWithId(injector: Injector): SerializedInjector | null { + if (isElementInjector(injector)) { + return serializeElementInjectorWithId(injector); + } else { + return serializeEnvironmentInjectorWithId(injector); + } +} + +function serializeEnvironmentInjectorWithId(injector: Injector): SerializedInjector | null { + const id = getOrCreateInjectorId(injector, injector); + + const serializedInjector = serializeInjector(injector); + if (serializedInjector === null) { + return null; + } + + return {id, ...serializedInjector}; +} + +function isInjectionToken(token: Type | InjectionToken): boolean { + return token.constructor.name === 'InjectionToken'; +} + +function isNullInjector(injector: Injector) { + const metadata = getInjectorMetadata(injector); + return metadata !== null && metadata.type === 'null'; +} + +function valueToLabel(value: any): string { + if (isInjectionToken(value)) { + const token = value.toString(); + + // This logic relies on the current InjectionToken.toString implementation. + if (token.startsWith('InjectionToken')) { + const tokenName = token.replace('InjectionToken', '').trim(); + return `InjectionToken (${tokenName})`; + } + return token; + } + + if (typeof value === 'object') { + return stripUnderscore(value.constructor.name); + } + + if (typeof value === 'function') { + return stripUnderscore(value.name); + } + + if (typeof value !== 'string') { + return String(value); + } + + return stripUnderscore(value); +} + +function stripUnderscore(str: string): string { + if (str.startsWith('_')) { + return str.slice(1); + } + + return str; +} diff --git a/devtools/projects/ng-devtools-backend/src/lib/profiling/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/lib/profiling/BUILD.bazel index e78f3351f02..6688f58bc50 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/profiling/BUILD.bazel +++ b/devtools/projects/ng-devtools-backend/src/lib/profiling/BUILD.bazel @@ -13,8 +13,8 @@ ts_project( deps = [ "//devtools/projects/ng-devtools-backend/src/lib/config", "//devtools/projects/ng-devtools-backend/src/lib/directive-forest:manager", - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree", "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/identity-tracker", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils:directive", "//devtools/projects/ng-devtools-backend/src/lib/profiling/profiler", "//devtools/projects/ng-devtools-backend/src/lib/shared:interfaces", "//devtools/projects/ng-devtools-backend/src/lib/shared/highlighter", diff --git a/devtools/projects/ng-devtools-backend/src/lib/profiling/capture.ts b/devtools/projects/ng-devtools-backend/src/lib/profiling/capture.ts index 32638dc6de9..dafbed68d37 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/profiling/capture.ts +++ b/devtools/projects/ng-devtools-backend/src/lib/profiling/capture.ts @@ -21,7 +21,7 @@ import {isCustomElement, runOutsideAngular} from '../shared/utils/general'; import {DirectiveForestManager, getDirectiveForestManager} from '../directive-forest/manager'; import {IdentityTracker} from '../directive-forest/identity-tracker/identity-tracker'; import {getProfiler, Hooks} from './profiler'; -import {getDirectiveName} from '../directive-forest/component-tree/component-tree'; +import {getDirectiveName} from '../directive-forest/utils/directive'; import {debugLog} from '../shared/utils/log'; import {AngularDevtoolsError} from '../shared/utils/error'; diff --git a/devtools/projects/ng-devtools-backend/src/lib/profiling/cd-analyzer/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/lib/profiling/cd-analyzer/BUILD.bazel index 28bf6869e0f..fe4f0efb398 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/profiling/cd-analyzer/BUILD.bazel +++ b/devtools/projects/ng-devtools-backend/src/lib/profiling/cd-analyzer/BUILD.bazel @@ -10,8 +10,8 @@ ts_project( ), deps = [ "//devtools/projects/ng-devtools-backend/src/lib/config", - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree", "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/identity-tracker", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils:directive", "//devtools/projects/ng-devtools-backend/src/lib/profiling/profiler", "//devtools/projects/ng-devtools-backend/src/lib/shared:interfaces", "//devtools/projects/ng-devtools-backend/src/lib/shared/highlighter", diff --git a/devtools/projects/ng-devtools-backend/src/lib/profiling/cd-analyzer/highlighting.ts b/devtools/projects/ng-devtools-backend/src/lib/profiling/cd-analyzer/highlighting.ts index 0ca2bb685d8..2fb1292a235 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/profiling/cd-analyzer/highlighting.ts +++ b/devtools/projects/ng-devtools-backend/src/lib/profiling/cd-analyzer/highlighting.ts @@ -12,7 +12,7 @@ */ import {getConfig} from '../../config/config'; -import {getDirectiveName} from '../../directive-forest/component-tree/component-tree'; +import {getDirectiveName} from '../../directive-forest/utils/directive'; import {highlightElement, removeHighlightsByType} from '../../shared/highlighter'; import { changeDetectionHighlightTemplate, diff --git a/devtools/projects/ng-devtools-backend/src/lib/profiling/performance-track.ts b/devtools/projects/ng-devtools-backend/src/lib/profiling/performance-track.ts index c321018193e..daa3fe6d2a6 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/profiling/performance-track.ts +++ b/devtools/projects/ng-devtools-backend/src/lib/profiling/performance-track.ts @@ -8,7 +8,7 @@ import {LifecycleProfile} from '../../../../protocol'; import {getProfiler, Profiler} from './profiler'; -import {getDirectiveName} from '../directive-forest/component-tree/component-tree'; +import {getDirectiveName} from '../directive-forest/utils/directive'; import type {ComponentInstance, DirectiveInstance} from '../shared/interfaces'; import {getConfig} from '../config/config'; diff --git a/devtools/projects/ng-devtools-backend/src/lib/shared/highlighter/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/lib/shared/highlighter/BUILD.bazel index 8957dc7a9a6..9ecf5350338 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/shared/highlighter/BUILD.bazel +++ b/devtools/projects/ng-devtools-backend/src/lib/shared/highlighter/BUILD.bazel @@ -11,7 +11,7 @@ ts_project( ], deps = [ "//:node_modules/@angular/core", - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils:directive", "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:error", "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:general", "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:log", diff --git a/devtools/projects/ng-devtools-backend/src/lib/shared/highlighter/index.ts b/devtools/projects/ng-devtools-backend/src/lib/shared/highlighter/index.ts index ccfb50dcddb..b6f39b362a8 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/shared/highlighter/index.ts +++ b/devtools/projects/ng-devtools-backend/src/lib/shared/highlighter/index.ts @@ -15,7 +15,7 @@ import { HighlightType, } from './highlights'; import {createOverlayWithLabels, getComponentRect} from './dom'; -import {findDirectiveAndHost} from '../../directive-forest/component-tree/component-tree'; +import {findDirectiveAndHost} from '../../directive-forest/utils/directive'; import {runOutsideAngular} from '../utils/general'; import {debugLog} from '../utils/log'; diff --git a/devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api/BUILD.bazel b/devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api/BUILD.bazel index b036f7e133b..09259cf47a0 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api/BUILD.bazel +++ b/devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api/BUILD.bazel @@ -11,7 +11,7 @@ ng_project( deps = [ "//:node_modules/@angular/core", "//devtools/projects/ng-devtools-backend/src/lib/directive-forest:core-enums", - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree:get-roots", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/utils:app-roots", "//devtools/projects/ng-devtools-backend/src/lib/shared/utils:error", "//devtools/projects/protocol", ], diff --git a/devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api/ng-debug-api.ts b/devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api/ng-debug-api.ts index 4d2b2453c80..1b1c492fa7a 100644 --- a/devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api/ng-debug-api.ts +++ b/devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api/ng-debug-api.ts @@ -7,7 +7,7 @@ */ import type {ɵFrameworkAgnosticGlobalUtils as GlobalUtils} from '@angular/core'; -import {getAppRoots} from '../../directive-forest/component-tree/get-roots'; +import {getAppRoots} from '../../directive-forest/utils/app-roots'; import {Framework} from '../../directive-forest/core-enums'; import {AngularDevtoolsError} from '../utils/error'; diff --git a/devtools/projects/ng-devtools-backend/src/public-api.ts b/devtools/projects/ng-devtools-backend/src/public-api.ts index 1432ea7e2e2..1c21af93000 100644 --- a/devtools/projects/ng-devtools-backend/src/public-api.ts +++ b/devtools/projects/ng-devtools-backend/src/public-api.ts @@ -11,7 +11,7 @@ */ export * from './lib'; -export {findNodeFromSerializedPosition} from './lib/directive-forest/component-tree/component-tree'; +export {findNodeFromSerializedPosition} from './lib/directive-forest'; export {viewSourceFromRouter} from './lib/client-event-subscribers'; export {type RoutePropertyType} from './lib/router-tree/router-tree'; export type {DevtoolsBackendConfig} from './lib/shared/interfaces'; diff --git a/devtools/projects/shell-browser/src/app/BUILD.bazel b/devtools/projects/shell-browser/src/app/BUILD.bazel index 456a0b969bc..d11b5cc50b9 100644 --- a/devtools/projects/shell-browser/src/app/BUILD.bazel +++ b/devtools/projects/shell-browser/src/app/BUILD.bazel @@ -95,7 +95,8 @@ ts_project( ], deps = [ "//devtools/projects/ng-devtools-backend", - "//devtools/projects/ng-devtools-backend/src/lib/directive-forest/component-tree", + "//devtools/projects/ng-devtools-backend/src/lib/directive-forest", + "//devtools/projects/ng-devtools-backend/src/lib/injector-tree", "//devtools/projects/ng-devtools-backend/src/lib/shared/ng-debug-api", "//devtools/projects/protocol", ], diff --git a/devtools/projects/shell-browser/src/app/chrome-window-extensions.ts b/devtools/projects/shell-browser/src/app/chrome-window-extensions.ts index 70b1ff16617..e26e0abc929 100644 --- a/devtools/projects/shell-browser/src/app/chrome-window-extensions.ts +++ b/devtools/projects/shell-browser/src/app/chrome-window-extensions.ts @@ -9,10 +9,10 @@ import {RoutePropertyType, viewSourceFromRouter} from '../../../ng-devtools-backend'; import { buildDirectiveForest, - getInjectorFromElementNode, findNodeFromSerializedPosition, queryDirectiveForest, -} from '../../../ng-devtools-backend/src/lib/directive-forest/component-tree/component-tree'; +} from '../../../ng-devtools-backend/src/lib/directive-forest'; +import {getInjectorFromElementNode} from '../../../ng-devtools-backend/src/lib/injector-tree/injector-tree'; import {ElementPosition, SignalNodePosition} from '../../../protocol'; import {ngDebugClient} from '../../../ng-devtools-backend/src/lib/shared/ng-debug-api/ng-debug-api';