# ESLint plugin

`@dsivd/prestations-ng` ships an ESLint plugin with rules that catch signal misuses the
Angular compiler lets through, plus the lint setup shared by every project built on the
library. It is published as a subpath of the library, so both follow the version of the
library.

## Setup

The plugin exposes **shareable configs**, in the same spirit as `angular-eslint`. Add them to
the `extends` of the `**/*.ts` and `**/*.html` blocks of your `eslint.config.mjs`:

```ts
import angular from 'angular-eslint';
import tseslint from 'typescript-eslint';
import prestationsNg from '@dsivd/prestations-ng/eslint';

export default tseslint.config(
    {
        files: ['**/*.ts'],
        extends: [...prestationsNg.configs.tsRecommended],
        languageOptions: {
            parserOptions: {
                projectService: true,
                tsconfigRootDir: import.meta.dirname,
            },
        },
        processor: angular.processInlineTemplates,
    },
    {
        files: ['**/*.html'],
        extends: [...prestationsNg.configs.templateRecommended],
    },
);
```

That is all. You do **not** declare `plugins`, and you do **not** list the rules — both come
from the config. Inline templates written in a `@Component` are covered too, through
`angular.processInlineTemplates`.

> 🚨 **Do not spread `angular.configs.tsRecommended` or `angular.configs.templateRecommended`
> alongside these configs.** They already include them. Declaring the same plugin twice from
> two different copies makes ESLint fail outright, before linting anything.

> 🚨 **Prerequisite**: `lintFilePatterns` in your `angular.json` must include
> `src/**/*.html`. Without it `ng lint` never opens your templates, and the template rules
> silently never run.

## The configs

| Config                        | Target      | Contents                                                       |
| ----------------------------- | ----------- | -------------------------------------------------------------- |
| `configs.tsRecommended`       | `**/*.ts`   | the baselines, the house style, and `tsRules`                  |
| `configs.templateRecommended` | `**/*.html` | the baselines, the house style, and `templateRules`            |
| `configs.tsRules`             | `**/*.ts`   | `no-direct-signal-mutation`                                    |
| `configs.templateRules`       | `**/*.html` | `no-direct-signal-mutation`, `no-uninvoked-signal-in-template` |

The `*Recommended` presets are what a project normally extends. On top of the rules written
here they bring:

- the baselines — `eslint.configs.recommended`, `typescript-eslint` recommended and
  stylistic, `angular-eslint` recommended, and for templates its accessibility set;
- the house style — naming and selector conventions, import ordering
  (`simple-import-sort`, `import-x`), rxjs conventions, and the signal rules of
  `angular-eslint` (`no-uncalled-signals`, `prefer-signals`, `prefer-signal-model`).

Use `tsRules` / `templateRules` instead when a project supplies its own style and only wants
the rules of this library. They register the plugin and nothing else, so you keep control of
the baselines — and stay responsible for keeping them aligned.

`no-direct-signal-mutation` appears in both targets: the rule carries one visitor for
TypeScript and one for the Angular template AST, and each fires on its own kind of file.

## What happens when you update the library

A new rule added to the library lands in the config, so `npm update @dsivd/prestations-ng`
**will make your lint fail** on the code that violates it. This is intentional: it is how a
new practice gets rolled out across every project using the library. Every added rule is
listed in the [CHANGELOG](CHANGELOG.md).

If you cannot fix the violations right away, turn the rule off — or lower its severity — in
your own `rules` block. It is applied after the shared config, so it wins:

```ts
{
    files: ['**/*.html'],
    extends: [...prestationsNg.configs.templateRecommended],
    rules: {
        // decided by this project, survives library updates
        '@dsivd/prestations-ng/no-direct-signal-mutation': ['off'],
    },
},
```

## Rules

### `no-direct-signal-mutation`

Reports a mutation of the value held by a signal, in either of its two forms: an
assignment into one of its members, or a call to an in-place mutator. Mutating that value
does not notify the signal's dependents, so the view is not refreshed.

Applies to **TypeScript files and templates**, including the case where the mutation hides
in a two-way binding.

```ts
// ✗ mutates the object inside the signal, no notification
this.model().property = value;
this.model().items.splice(index, 1);

// ✓
this.model.update((current) => ({ ...current, property: value }));
this.model.update((current) => ({
    ...current,
    items: current.items.filter((_, i) => i !== index),
}));
```

```html
<!-- ✗ -->
<button (click)="model().property = value">…</button>
<button (click)="model().items.splice(index, 1)">…</button>
<input [(ngModel)]="model().property" />

<!-- ✓ -->
<button (click)="model.update((v) => ({ ...v, property: value }))">…</button>
```

All the assignment operators accepted by the Angular expression parser are covered: `=`,
`+=`, `-=`, `*=`, `/=`, `%=`, `**=`, `&&=`, `||=`, `??=`.

The in-place mutators covered are those of `Array` — `push`, `pop`, `shift`, `unshift`,
`splice`, `sort`, `reverse`, `fill`, `copyWithin` — and of `Map` / `Set` — `set`, `add`,
`delete`, `clear`. Their non-mutating counterparts, `toSorted`, `toReversed`, `filter`,
`concat`, `with`, are never reported: they return a new value. `items()["push"](x)` is the
same call as `items().push(x)` and is reported alike.

Two other ways of writing into the value are covered, in TypeScript — the Angular template
parser accepts neither:

```ts
delete this.model().users[0];
Object.assign(this.model(), { property: value });
```

#### Names bound to the value

A mutation is rarely written on the signal read itself. The rule follows the value through
the bindings it can resolve exactly, and only those:

```ts
// ✗ a variable written once
const users = this.model().users;
users.push(user);

// ✗ the element parameter of an iteration callback
this.model().users.forEach((user) => (user.done = true));
```

```angular-html
<!-- ✗ a @for item, bound only inside its own block -->
@for (user of model().users; track user.id) {
    <input [(ngModel)]="user.done" />
    <button (click)="user.tags.push(tag)">…</button>
}

<!-- ✗ a @let -->
@let users = model().users;
<button (click)="users.push(user)">…</button>
```

In TypeScript these come from ESLint's scope analysis, in templates from the block that
introduces the name — nothing is inferred from a naming convention. A variable that is
**reassigned** is dropped: the name may hold something else by the time it is mutated. Same
for `reduce`, whose first parameter is the accumulator and not an element.

**What it cannot follow** is a value crossing a function boundary — handed to a method,
stored in a class field, returned and mutated elsewhere:

```ts
// not reported: the rule cannot know what `sortInto` does
this.sortInto(this.model().users);
```

That needs interprocedural analysis, which ESLint does not provide; a full type checker
would be required. It is the one remaining gap in detection.

#### Only real signals are inspected

The rule does not guess from the shape of a call. It reads the declaring class — the linted
file itself, or the component a template belongs to — and resolves its signal members
through the whole inheritance chain, the way TypeScript would: relative paths,
`node_modules`, `paths` mappings, and the flattened `.d.ts` of a published library. Nothing
has to be declared by hand.

**No signal's value is to be mutated, whatever its kind** — a mutation notifies none of its
dependents. The kinds differ only in the advice the message carries, since none but the
first has a `.set()`:

| Declared as                             | On a mutation of its value                                  |
| --------------------------------------- | ----------------------------------------------------------- |
| `signal()`, `model()`, `linkedSignal()` | use `.set()` / `.update()`                                  |
| `computed()`                            | the value is derived: mutate the signal it is computed from |
| `input()`                               | the value belongs to the parent: ask through an `output()`  |
| `toSignal()`                            | the value comes from the observable: change it upstream     |
| `viewChild()`, `contentChildren()`, …   | **the one exception**, left alone: see below                |

A view query is the exception because it hands out a DOM element or a component instance,
and mutating that is the reason for asking for it: `rows().nativeElement.hidden = true` is
the normal way to use one. `.required` variants included.

Anything that is not a declared signal is left alone as well:

| Expression                           | Why                                                          |
| ------------------------------------ | ------------------------------------------------------------ |
| `this.getConfig().items.push(item)`  | `getConfig()` is a plain method, not a signal                |
| `map.get(key).files.push(file)`      | the call takes arguments, so it is not a signal read         |
| `component.model().items.push(item)` | reached through a foreign receiver, not the component itself |

Because the rule knows a real signal from an ordinary method, `set` / `add` / `delete` are
safe to report: `byId().set(k, v)` mutates the `Map` inside the signal, while `byId.set(m)`
replaces the signal's value and is correct.

**One accepted false positive.** A `computed()` may legitimately hand out a live mutable
object, and no type information is available to tell that apart from a derived value:

```ts
readonly items = computed(() => this.form.get('items') as FormArray);
this.items().push(control); // reported, though this is the FormArray API
```

**One accepted gap, and it is forced.** A published declaration file spells a `computed()`,
a `toSignal()` and a view query alike, `Signal<T>` — the factory name is gone. A signal
**inherited from a package** and known by its type only is therefore left alone:

```ts
// in the published .d.ts, indistinguishable from one another
readonly fieldId: Signal<string>; // was a computed()
readonly inputElement: Signal<ElementRef>; // was a viewChild()
```

Reporting that group would break the lint of every project extending a component of this
library: `prestations-ng` publishes 54 view queries, `AbstractPageComponent` and
`FoehnInputComponent` among them, and touching the element they queried is normal code. So
a mutation of an inherited `computed()` goes unreported — the narrower harm of the two.
Signals declared in your own project, base classes included, are unaffected: their factory
call is right there to be read.

The rule has no autofix: the correct rewrite depends on what you meant.

**When the declaring class cannot be read** — an unsaved buffer, a template with no twin
`.ts` — its signals are unknown, and the rule falls back to treating any argument-less
accessor on the component as a signal. It may then report a plain method. That direction is
deliberate: a false positive costs one `eslint-disable-next-line`, a missed mutation is a
silent bug.

### `no-uninvoked-signal-in-template`

Reports a signal referenced in a template without being called. A bare reference evaluates
to the function itself: always truthy, and serialized as source code when interpolated.

Applies to **templates only** (external and inline).

```html
<!-- ✗ -->
<p>{{ userName }}</p>
<p>{{ userName + '!' }}</p>
<div [hidden]="!isLoading">…</div>

<!-- ✓ -->
<p>{{ userName() }}</p>
<p>{{ userName() + '!' }}</p>
<div [hidden]="!isLoading()">…</div>
```

A control flow condition counts too: `@if (isLoading)` must be `@if (isLoading())`.

The Angular compiler only covers part of these cases (`NG8109` / `NG8117`): it lets the
negation and the concatenation through.

The rule is **autofixable** — `npm run lint` with `--fix` adds the missing parentheses.

Signal names are resolved automatically, with no configuration: the rule reads the twin
`.ts` of the template and walks its whole inheritance chain, resolving each `extends` the
way TypeScript would — relative paths, `node_modules`, `paths` mappings. Signals inherited
from `FoehnInputComponent`, `AbstractPageComponent` or from one of your own base classes are
found without declaring anything.

**Not reported:**

| Expression                                                   | Why                                                                                       |
| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------- |
| `mySignal()`, `mySignal?.()`                                 | already called                                                                            |
| `mySignal.set(…)`, `.update(…)`, `.asReadonly()`             | targets the signal, not its value                                                         |
| `[(value)]="mySignal"`                                       | a writable signal is two-way bound **without** parentheses, Angular calls `.set()` itself |
| `#ref`, `@for` items, `@if … as`, `@let`, `let-x`, `$index`… | template-local names shadow the class members                                             |

## The TypeScript counterpart

`@angular-eslint/no-uncalled-signals` covers the same class of bug **in TypeScript**, using
the real type checker — far more reliable than what a template rule can do. It cannot run on
templates: it requires type information, which a `.html` file has no program for. The two
are complementary, not redundant.

`configs.tsRecommended` already enables it. With `configs.tsRules` you enable it yourself:

```ts
'@angular-eslint/no-uncalled-signals': 'error',
```

It only reports signals used in logic positions (`if`, `!x`, `&&`, `===`, `.length`…), not a
bare `const x = mySignal`.
