Skip to content

Commit 9fff774

Browse files
committed
fix(injectors): tell apart DI tokens that share a name
Two tokens with the same name, such as two `new InjectionToken('config')`, collided: the injected pairs were keyed `injector|name`, so injecting one token let "Show value" and "Store as global" read (and create) the other, and a provider value read checked only the name at its index. Give each token object a stable id on the page through a WeakMap (`token-id.ts`, `tok-N`) and carry it as `tokenId` on providers and dependencies. Key the injected pairs and the provider value check by it, and keep it through the server's report checks. The agent tools still take a token name: `read-provider-value` and `explain-injection` answer a shared name with the candidates and their ids and take `tokenId` to pick one, and `inspect-providers` lists each match with its id and takes `tokenId` to keep one. Reports without ids fall back to names. The panel keys provider rows by id and sends it with value reads. Refs #367
1 parent 9185684 commit 9fff774

22 files changed

Lines changed: 717 additions & 60 deletions

‎app/src/__tests__/store-history.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,25 @@ describe('Provider value', () => {
414414
expect(region.textContent).toContain('id:');
415415
});
416416

417+
it('sends the token id, and closes when another token with the same name takes the row', async () => {
418+
const call = vi.fn(async () => ({ ok: true, type: 'Object', members: [] }));
419+
const fixture = await mount(call);
420+
fixture.componentRef.setInput('tokenId', 'tok-3');
421+
await settle(fixture);
422+
const toggle = button(fixture, 'Show the value of CartService');
423+
toggle.click();
424+
await settle(fixture);
425+
expect(call).toHaveBeenCalledWith('request-provider-value', {
426+
pageId: 'p1',
427+
request: { injectorId: 'inj-1', token: 'CartService', tokenId: 'tok-3', index: 2, path: [] },
428+
});
429+
expect(toggle.getAttribute('aria-expanded')).toBe('true');
430+
// Same name and index, different token (#367): the open value belonged to the other one.
431+
fixture.componentRef.setInput('tokenId', 'tok-4');
432+
await settle(fixture);
433+
expect(toggle.getAttribute('aria-expanded')).toBe('false');
434+
});
435+
417436
it('shows only the latest read when it is closed and reopened while a read is pending', async () => {
418437
const pending: ((answer: unknown) => void)[] = [];
419438
const call = vi.fn(() => new Promise((resolve) => pending.push(resolve)));

‎app/src/pages/di-inspector.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ import { StartupSection } from './startup-section';
3232

3333
interface ProviderInfo {
3434
token: string;
35+
/** The page's id for the token object; two tokens can share a name. Missing in older reports. */
36+
tokenId?: string;
3537
type: string;
3638
isViewProvider: boolean;
3739
multi?: boolean;
@@ -42,6 +44,7 @@ interface ProviderInfo {
4244
interface DependencyInfo {
4345
from: string;
4446
token: string;
47+
tokenId?: string;
4548
flags: string[];
4649
providedBy: string | null;
4750
}
@@ -457,7 +460,10 @@ function isTree(value: unknown): value is InjectorNode[] {
457460
}
458461
@if (sel.dependencies?.length) {
459462
<ul class="deps">
460-
@for (dep of sel.dependencies; track dep.from + dep.token + $index) {
463+
@for (
464+
dep of sel.dependencies;
465+
track dep.from + (dep.tokenId ?? dep.token) + $index
466+
) {
461467
<li class="dep" [class.hit]="matches(dep.token)">
462468
<div class="dep-main">
463469
<span class="token mono">{{ dep.token }}</span>
@@ -512,7 +518,11 @@ function isTree(value: unknown): value is InjectorNode[] {
512518
}
513519
@if (providerCount(sel)) {
514520
<ul class="providers">
515-
@for (p of sel.providers; track p.token + $index; let index = $index) {
521+
@for (
522+
p of sel.providers;
523+
track (p.tokenId ?? p.token) + $index;
524+
let index = $index
525+
) {
516526
@if (!isHidden(p)) {
517527
<li class="provider" [class.hit]="matches(p.token)">
518528
<div class="dep-main">
@@ -541,6 +551,7 @@ function isTree(value: unknown): value is InjectorNode[] {
541551
kind: 'provider',
542552
injectorId: sel.injector.id,
543553
token: p.token,
554+
tokenId: p.tokenId,
544555
index: index,
545556
}"
546557
[label]="p.token + positionSuffix(sel.providers, index)"
@@ -551,6 +562,7 @@ function isTree(value: unknown): value is InjectorNode[] {
551562
[pageId]="shownPageId()"
552563
[injectorId]="sel.injector.id"
553564
[token]="p.token"
565+
[tokenId]="p.tokenId"
554566
[index]="index"
555567
[position]="tokenPosition(sel.providers, index)"
556568
/>

‎app/src/pages/di-provider-value.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,8 @@ export class ProviderValue {
203203
readonly pageId = input<string | null>(null);
204204
readonly injectorId = input.required<string>();
205205
readonly token = input.required<string>();
206+
/** The page's id for the token, which the page matches before the name. */
207+
readonly tokenId = input<string | undefined>(undefined);
206208
/** The provider's index in its injector's `providers`. */
207209
readonly index = input.required<number>();
208210
/** Tells apart providers of one token (multi providers), such as `(2 of 2)`. */
@@ -217,7 +219,7 @@ export class ProviderValue {
217219

218220
/** The provider this shows; another one closes it. */
219221
readonly key = computed(
220-
() => `${this.pageId()}|${this.injectorId()}|${this.index()}|${this.token()}`,
222+
() => `${this.pageId()}|${this.injectorId()}|${this.index()}|${this.tokenId() ?? this.token()}`,
221223
);
222224
readonly open = linkedSignal<string, boolean>({ source: this.key, computation: () => false });
223225
readonly answer = linkedSignal<string, MembersAnswer | null>({
@@ -263,6 +265,7 @@ export class ProviderValue {
263265
request: {
264266
injectorId: this.injectorId(),
265267
token: this.token(),
268+
...(this.tokenId() ? { tokenId: this.tokenId() } : {}),
266269
index: this.index(),
267270
...request,
268271
},

‎app/src/ui/store-global.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { isStaticReport } from '../rpc';
55
/** What the page stores: a component, a provider or NgRx state (see `console-handles.ts`). */
66
export type ConsoleTarget =
77
| { kind: 'component'; id: string }
8-
| { kind: 'provider'; injectorId: string; token: string; index: number }
8+
| { kind: 'provider'; injectorId: string; token: string; index: number; tokenId?: string }
99
| { kind: 'ngrx'; storeId: string };
1010

1111
interface StoreResult {

‎apps/docs/src/content/agents/tools.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -499,12 +499,17 @@ The injectors a page reported. Element injectors list what each component inject
499499
| ---------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
500500
| `injector` | no | A tag name, a component or directive class name, an environment injector name like `Root`, `Platform` or `Route: admin`, an injector id, or a component instance id like `c12`. Returns only the matching injectors. |
501501
| `token` | no | A token name, like `HttpClient`. Returns the injectors that provide it and the components or services that inject it. |
502+
| `tokenId` | no | The id of one token, like `tok-3`, from `tokenId` in the tree. Keeps only that token when several share a name. |
502503

503504
An `injector` that names an element injector returns it with its lookup path resolved to names and provided tokens. One that names an environment injector, in any case, returns that injector's providers, what the services it already created inject, and its parent injectors. When nothing matches, the answer lists the tags and environment injector names on the page to retry with.
504505

505506
An element injector that belongs to a component carries `componentId`, the instance id that `inspect-component`, `list-components` and the `component-tree` resource use. `framework: true` marks the injectors and providers that come from the installed `@angular/*` packages; see [Framework injectors](../inspectors/injectors.md#framework-injectors).
506507

507-
Without `injector` or `token`, the answer is the whole tree and says which change detection mode the page runs. The answer stays within 20,000 characters and its JSON always parses. A larger tree shows element injectors as an outline (id, name, type, component, and provider and dependency counts), and when that is still too long it leaves out the deepest injectors and says how many. The environment injectors are always there, as an outline when they are large, and without their deepest injectors when even that outline is too long. An `injector` or `token` answer that is too long cuts each injector's `providers` and `dependencies` lists, with `providersTotal` and `dependenciesTotal` giving the full counts, so a large injector such as `Root` still shows. An `@ngrx/signals` store that an environment injector created carries the name the NgRx tools use, such as `TravelStore`, in `token`, and its class name `SignalStore` in `tokenClass`; `token` finds it by either name, and so do `read-provider-value` and `explain-injection`. `injector` and `token` take at most 500 characters each. When the page reported only part of its injector tree (it keeps at most 2000 element injectors and 2500 in all, and leaves out injectors nested more than 1000 levels deep), the answer says so.
508+
Without `injector` or `token`, the answer is the whole tree and says which change detection mode the page runs. The answer stays within 20,000 characters and its JSON always parses. A larger tree shows element injectors as an outline (id, name, type, component, and provider and dependency counts), and when that is still too long it leaves out the deepest injectors and says how many. The environment injectors are always there, as an outline when they are large, and without their deepest injectors when even that outline is too long. An `injector` or `token` answer that is too long cuts each injector's `providers` and `dependencies` lists, with `providersTotal` and `dependenciesTotal` giving the full counts, so a large injector such as `Root` still shows. An `@ngrx/signals` store that an environment injector created carries the name the NgRx tools use, such as `TravelStore`, in `token`, and its class name `SignalStore` in `tokenClass`; `token` finds it by either name, and so do `read-provider-value` and `explain-injection`. `injector` and `token` take at most 500 characters each.
509+
510+
Each provider and dependency carries `tokenId`, the page's id for the token object, so two tokens with the same name, such as two `new InjectionToken('config')`, stay apart. A `token` that several tokens share lists every match with its `tokenId`, and `tokenId` keeps one of them. `read-provider-value` and `explain-injection` answer such a name with the candidates instead, and take `tokenId` to pick one. Ids last until the page reloads. A tree from an older overlay has no ids, and the tools match by name.
511+
512+
When the page reported only part of its injector tree (it keeps at most 2000 element injectors and 2500 in all, and leaves out injectors nested more than 1000 levels deep), the answer says so.
508513

509514
### read-provider-value
510515

@@ -513,6 +518,7 @@ The current value of a service or other provider that an injector on the page al
513518
| Argument | Required | Value |
514519
| ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
515520
| `token` | yes | A class name like `CartStore` or an `InjectionToken` description like `API_URL`. |
521+
| `tokenId` | no | The id of one token, like `tok-3`. Needed when several tokens share the name; the answer then lists them. |
516522
| `injector` | no | An injector id, `Root`, `Platform`, `Route: admin`, a tag or a component class name. Defaults to the first injector that provides the token, environment injectors first. |
517523
| `path` | no | A member, then keys or indexes, like `items` or `cart.items[0]`. Without it, the answer lists the members. |
518524
| `depth` | no | With `path`, the levels to read below it, 1 to 5. |
@@ -528,6 +534,7 @@ How Angular resolves one token for one component, element or environment injecto
528534
| ---------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
529535
| `injector` | yes | Where the injection happens: a component or directive class name, a tag, a component instance id like `c12` (an error's owner id works), an injector id, or an environment injector name like `Root`. |
530536
| `token` | yes | The token as the Injectors tab names it: a class name like `HttpClient` or an `InjectionToken` description like `API_URL`. |
537+
| `tokenId` | no | The id of one token, like `tok-3`. Needed when several tokens share the name; the answer then lists them. |
531538
| `self` | no | `true` asks only the first injector. |
532539
| `skipSelf` | no | `true` starts at the parent injector. |
533540
| `host` | no | `true` stops at the host element of the component that declares the start, where only its `viewProviders` and the component count. |

‎apps/docs/src/content/inspectors/injectors.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ For environment injectors, **Injected by its services** lists what the services
8181

8282
Each live provider row has a **Show value** button. It reads the provider's current value from the page and lists it like the properties of a component: its own fields, with signals and resources unwrapped (marked **signal** or **resource**), and methods left out. An object, array, Map or Set opens one level at a time, and each level is read from the page when you open it. A value without fields, such as a string or an array from `useValue`, shows whole. **Refresh** reads it again, since the list does not follow the app on its own. When several providers share a token, as `multi` providers do, their buttons and values are named with their position, such as **(2 of 2)**.
8383

84+
Two tokens can have the same name, such as two `new InjectionToken('config')`. The overlay gives each token object its own id (`tokenId` in the injector tree, such as `tok-3`), so the value, the **Injected here** rows and the check for whether something injected a token follow the token itself, not its name. Their buttons are named with their position, like the providers of one token.
85+
8486
Reading never creates a provider, with the same rules as **Store as global** below. A provider the app has not created yet says **… has not been created yet** instead. Getters never run, and secret-looking names and values are shown as `[redacted]`. See [what the devtools redact](../security.md).
8587

8688
### Store a provider as a global
@@ -222,7 +224,7 @@ If the selected injector leaves the page because its component or directive was
222224
| `pangular:scan-providers` | tool | DI providers from source: `@Injectable` services, `inject()` calls, constructor parameters and `providers` arrays. |
223225
| `pangular:explain-injection` | tool | The lookup of one token from a component, element or environment injector, step by step, with `self`, `skipSelf`, `host` and `optional`. Says at each injector whether it provides the token and why the lookup stops. See [Explain a lookup with flags](#explain-a-lookup-with-flags). |
224226
| `pangular:inspect-providers` | tool | The injector tree a page reported, with what components and created services inject. `injector` narrows it to matching element or environment injectors (`Root`, `Platform`, `Route: admin`) or a component instance id, `token` to where a token is provided and injected. `componentId` and `framework` mark the owning component and Angular's own injectors and providers. |
225-
| `pangular:read-provider-value` | tool | The current value of a provider an injector already created, by `token` and optional `injector`, with `path` to read deeper. See [Peek at a provider value](#peek-at-a-provider-value). |
227+
| `pangular:read-provider-value` | tool | The current value of a provider an injector already created, by `token` and optional `injector`, with `path` to read deeper. When two tokens share the name, it lists them with their `tokenId`; pass `tokenId` to pick one. See [Peek at a provider value](#peek-at-a-provider-value). |
226228
| `pangular:startup-timing` | tool | How the page started: milestones from navigation start to the first stable state, and the slowest providers to construct with own and total time. See [Startup timing](#startup-timing). |
227229
| `pangular:injector-tree` | resource | The live tree last reported by a page. |
228230

‎packages/devtools/CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ What remains: `/config` exports `DEFAULT_POPUP_HOTKEY`, `PANGULAR_ACTIONS`, `PAN
197197
- Signal graph edges name their nodes instead of positions.
198198
- `inspect-signals` reads the graph of a component the page is not showing: a `component` the component tree knows, or a component host matched by the new `selector` argument (CSS). A selector that matches no component host is refused at once (#367).
199199
- A `Store` provided in a route is found, and the DI tools keep each signal store's name instead of `SignalStore`.
200+
- Two DI tokens with the same name, such as two `new InjectionToken('config')`, no longer mix up provider values or which token something injected. The injector tree carries a `tokenId` for each token, `read-provider-value` and `explain-injection` list the candidates for a shared name and take `tokenId` to pick one, and `inspect-providers` takes `tokenId` to keep one (#367).
200201
- The SSR hydration count is right, and a request is no longer reported as a transfer cache hit when it was not.
201202
- A failed write answers with `isError: true`, and a failing call keeps its response body.
202203
- The Express hub turns itself off with a warning on a Node.js that can't load it, instead of crashing the server.

‎packages/devtools/src/__tests__/component-tree.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -392,11 +392,18 @@ describe('componentDetail', () => {
392392
{
393393
from: 'Card',
394394
token: 'Store',
395+
tokenId: expect.stringMatching(/^tok-/),
395396
flags: [],
396397
providedBy: expect.any(String),
397398
providedByName: 'Root',
398399
},
399-
{ from: 'Card', token: 'Widget', flags: ['optional'], providedBy: null },
400+
{
401+
from: 'Card',
402+
token: 'Widget',
403+
tokenId: expect.stringMatching(/^tok-/),
404+
flags: ['optional'],
405+
providedBy: null,
406+
},
400407
]);
401408
});
402409

0 commit comments

Comments
 (0)