# eslint-plugin-ts-fortress

ESLint rules that steer schema definitions toward
[`ts-fortress`](https://www.npmjs.com/package/ts-fortress) idioms. Every rule except
`prefer-schema-over-guard-chain` and `no-type-only-codec` (which only report) is
auto-fixable, and every rewrite is **type-preserving**.

## Installation

```sh
npm install --save-dev eslint-plugin-ts-fortress
```

Requires ESLint 9+ (flat config) and TypeScript. A configured TypeScript project
is not required: only `no-type-only-codec` reads type information, and without it
the rule checks less rather than failing (see
[Type information](#type-information)).

## Usage (flat config)

The plugin ships a `recommended` config preset that registers the plugin and
turns on **every** rule at `error`:

```ts
// eslint.config.mts
import { eslintPluginTsFortress } from 'eslint-plugin-ts-fortress';

export default [eslintPluginTsFortress.configs.recommended];
```

Since the preset is a plain flat-config object, individual rules can be
adjusted by a later config entry:

```ts
// eslint.config.mts
import {
    eslintPluginTsFortress,
    type EslintTsFortressRules,
} from 'eslint-plugin-ts-fortress';

export default [
    eslintPluginTsFortress.configs.recommended,
    {
        files: ['src/legacy/**'],
        rules: {
            'ts-fortress/prefer-canonical-length-constrained-type': 'off',
        } satisfies Partial<EslintTsFortressRules>,
    },
];
```

Or register the plugin yourself and pick the rules one by one:

```ts
// eslint.config.mts
import {
    eslintPluginTsFortress,
    type EslintTsFortressRules,
} from 'eslint-plugin-ts-fortress';

export default [
    {
        plugins: { 'ts-fortress': eslintPluginTsFortress },
        rules: {
            'ts-fortress/prefer-canonical-length-constrained-type': 'error',
        } satisfies Partial<EslintTsFortressRules>,
    },
];
```

## Rules

| Rule                                       | Description                                                                                    |
| :----------------------------------------- | :--------------------------------------------------------------------------------------------- |
| `prefer-canonical-length-constrained-type` | Normalize a length-constrained array combinator with degenerate bounds to its canonical form.  |
| `prefer-namespace-import`                  | Require `ts-fortress` to be imported as a namespace rather than by name.                       |
| `prefer-schema-over-guard-chain`           | Report a hand-written chain of type guards on one value once it is long enough to be a schema. |
| `no-type-only-codec`                       | Report a codec whose value nothing reads, only the type `TypeOf` derives from it.              |

### `prefer-canonical-length-constrained-type`

Several of ts-fortress's array combinators build the very same type once their
length arguments hit a degenerate value. The rule rewrites each of those to the
combinator that names the constraint directly:

| ❌ written as                 | ✅ canonical form        | why they are the same type                                         |
| :---------------------------- | :----------------------- | :----------------------------------------------------------------- |
| `minLengthArray(1, x)`        | `nonEmptyArray(x)`       | `NonEmptyArray<A>` is defined as `MinLengthArray<1, A>`            |
| `minLengthTuple(0, x)`        | `array(x)`               | `MinLengthTuple<0, A>` is `readonly A[]` — no constraint at all    |
| `maxLengthTuple(0, x)`        | `fixedLengthTuple(0, x)` | both are `readonly []`                                             |
| `boundedLengthTuple(n, n, x)` | `fixedLengthTuple(n, x)` | the length union collapses to its single member                    |
| `boundedLengthTuple(0, n, x)` | `maxLengthTuple(n, x)`   | `MaxLengthTuple<N, A>` is defined as `BoundedLengthTuple<0, N, A>` |

```ts
import * as t from 'ts-fortress';

// ❌
const Tags = t.minLengthArray(1, t.string());
const Rgb = t.boundedLengthTuple(3, 3, t.number());
const Page = t.boundedLengthTuple(0, 10, t.string());

// ✅
const Tags = t.nonEmptyArray(t.string());
const Rgb = t.fixedLengthTuple(3, t.number());
const Page = t.maxLengthTuple(10, t.string());
```

Each rewrite keeps the accepted values, the `defaultValue`, and the options
object exactly as they were. The only observable change is the default
`typeName` — and the `details.kind` of the length error derived from it — which
becomes the one that names the constraint actually being checked.

#### Why the branded `*Array` family is left alone

`boundedLengthArray(0, n, x)` and `boundedLengthArray(n, n, x)` look like the
same degenerate cases, but their types are branded rather than structural, and
the analogous rewrites would silently change them:

- `BoundedLengthArray<Min, Max, A>` is
  `MaxLengthArray<Max, A> & MinLengthArray<Min, A>`, so rewriting
  `boundedLengthArray(0, n, x)` to `maxLengthArray(n, x)` **drops** the
  `MinLengthArray<0, A>` brand — a widening.
- `FixedLengthArray<N, A>` additionally intersects the exact tuple
  `FixedLengthTuple<N, A>` for `N <= 10`, so rewriting
  `boundedLengthArray(n, n, x)` to `fixedLengthArray(n, x)` **adds** a
  constraint — a narrowing.

Neither is a pure rename, so the rule does not report them.

#### Bounds above the structural cap

The `*Tuple` combinators only encode lengths up to `10` (ts-type-forge's
`StructuralPrefixLength`); past that they fall back to an overload that drops
the constraint from the result type. The rule therefore only fires when the
bound it carries over to the other combinator is a literal within `0..10`.

#### Imports

Both the namespace style (`import * as t from 'ts-fortress'`) and named imports
— including aliases — are recognized, and the autofix reuses whatever binding
the file already has, adding `import { … } from 'ts-fortress';` only when a
named call needs one. With
[`prefer-namespace-import`](#prefer-namespace-import) on as well — as it is in
the `recommended` preset — such an import is rewritten to a namespace access on
a later fix pass.

#### The rule deliberately leaves alone

- non-degenerate bounds (`minLengthArray(2, …)`, `boundedLengthTuple(1, 3, …)`);
- computed bounds and calls with explicit type arguments, since the literal is
  what makes the two forms equivalent;
- `minLengthArray(1, …)` calls passing a `defaultValue`, because
  `nonEmptyArray` types that option as `NonEmptyTuple<A>` while
  `minLengthArray` types it as the branded `MinLengthArray<1, A>` — a blind
  rewrite could stop type-checking. A `typeName`-only options object is safe
  and is rewritten. (The other rewrites type `defaultValue` identically, so
  they keep it.)
- calls where the target name is already bound to something else at the call
  site.

### `prefer-namespace-import`

`ts-fortress` is meant to be reached through a namespace. Its exports are short,
generic names — `string`, `number`, `record`, `array`, `Type` — that collide with
globals and with local declarations the moment they are pulled into a file's
scope, and every schema in the wild reads `t.string()`. The rule makes that the
only spelling:

```ts
// ❌
import { record, string } from 'ts-fortress';

const User = record({ name: string() });

// ✅
import * as t from 'ts-fortress';

const User = t.record({ name: t.string() });
```

`import type * as t from 'ts-fortress';` is accepted too, and is what the
autofix writes when every offending import in the file is type-only. A namespace
import may carry any local name — the rule does not rename an existing one.

A default import is reported as well, and its references become the namespace
itself. `ts-fortress` has no default export, so such a file did not type-check
to begin with — the rewrite is what it was reaching for.

A bare `import 'ts-fortress';` is reported and **deleted**: it binds no name,
and `ts-fortress` declares `sideEffects: false`, so importing it for its own
sake does nothing.

The autofix rewrites every reference along with the import: aliases resolve back
to the canonical export (`import { nonEmptyArray as nea }` → `t.nonEmptyArray`),
shorthand properties are expanded (`{ string }` → `{ string: t.string }`), and
type positions need nothing special, since `t.Type` reads as a qualified name
there. Several ts-fortress imports in one file collapse into a single namespace
import; when the file already has one, the others merge into it under its name.

#### Options

```ts
'ts-fortress/prefer-namespace-import': ['error', { namespaceName: 'tf' }],
```

- `namespaceName` (default `'t'`) — the local name the autofix gives the
  namespace import it creates. A namespace import already in the file is reused
  under its own name, whatever this is set to.

#### When the fix is withheld

The rule still reports, but leaves the file alone, when the rewrite could not be
completed safely:

- the namespace name is already bound to something else, at the import or at any
  reference being rewritten (a fix would silently resolve to that binding);
- a binding is re-exported by name (`export { string };`), which no member access
  can spell;
- a value import would have to merge into an `import type * as t`, which cannot
  carry it;
- the file has two namespace imports of `ts-fortress`, or one declaration that
  mixes a namespace specifier with a named or default one.

### `prefer-schema-over-guard-chain`

A long chain of hand-written type guards is a shape declaration that cannot be
read as one:

```ts
// ❌
const isProject = (value: unknown): value is Project =>
    isRecord(value) &&
    hasKey(value, 'name') &&
    isString(value.name) &&
    hasKey(value, 'path') &&
    isString(value.path);

// ✅
const PROJECT = t.record({ name: t.string(), path: t.string() });
```

The length is the least of it. What the chain cannot do is say what was wrong:
it returns `false`, so the caller filtering on it drops the value silently, with
nothing left of which field was missing or what type it turned out to be. The
shape is declared and checked in the same breath, so it cannot be named, reused,
or read on its own. `validate` returns structured `ValidationError`s, ready for
`validationErrorsToMessages`.

The rule reports; there is no fix. Writing the schema is the work, and it is not
mechanical — the chain says what the value must _have_, never what it _is_, so
an optional member, a union, and a member that is simply never checked are
indistinguishable from the guards alone.

#### What is counted

Guards within one `&&` chain, or one `||` chain of negated guards — the
early-return spelling of the same check — grouped by the identifier their first
argument is rooted at, so `hasKey(a, 'b')` and `isString(a.b)` count together
while guards on two different values do not add up.

A whole function body is deliberately not the unit. The same value checked once
per field across a `fill`-style function is a series of defaults rather than a
shape check, and measuring both units over one repository showed those to be
almost all of what a function-scoped count reports.

#### Options

```ts
'ts-fortress/prefer-schema-over-guard-chain': ['error', { threshold: 4 }],
```

- `threshold` (default `5`) — the number of guards on one value at which a
  single chain is reported.
- `guards` (default: the `ts-data-forge` narrowing helpers — `hasKey`,
  `isRecord`, `isString`, `isNumber`, `isBoolean`, `isBigint`, `isSymbol`,
  `isArray`, `isNonEmpty`, `isNonNullish`, `isNotNull`, `isNotUndefined`,
  `isPrimitive`) — the names to count, replacing the default list. A member call
  is matched on its property name, so `Arr.isArray` is named `isArray`.

The default threshold comes from a distribution rather than from taste. Counted
over the 3420 files of the repository this rule was written in, as they stood
before it was applied to them:

| guards | chains |
| -----: | -----: |
|      1 |    103 |
|      2 |     41 |
|      3 |     17 |
|      4 |      1 |
|      5 |      1 |
|     6+ |      0 |

One and two are ordinary narrowing and reporting them would be noise; three is
still common enough to be a style rather than a smell. Four and five have one
chain each, and they differ in exactly the way the threshold has to: the chain
of four narrows a value that is already typed, which is the case this rule is
least interested in, while the chain of five narrows the result of a
`JSON.parse` — the case it exists for. So the default sits between them, at the
length of the chain that prompted the rule. That chain of five is the one site
the rule reported when it was turned on, and it has since been rewritten.

### `no-type-only-codec`

A codec exists to check values at runtime. One whose value nothing reads — it is
there only so that `t.TypeOf` can derive a type from it — is a type written the
long way round: it costs a runtime object, keeps `ts-fortress` in the bundle of
whatever imports it, and reads as if something validated with it.

```ts
// ❌ — every import of `User` elsewhere is `import type`
export const User = t.record({ name: t.string() });

export type User = t.TypeOf<typeof User>;

// ✅
export type User = Readonly<{ name: string }>;
```

The rule looks at a top-level `const X` paired with a top-level
`type Y = t.TypeOf<typeof X>` — `Y` is usually `X` itself, or `X` is named
`yTypeDef` — and reports `X` when none of these reads its value:

- **its own file**: any reference outside a type. `typeof X` in another type
  does not count; `t.array(X)` in another codec does.
- **the other files of the TypeScript project**: an import that is not
  `import type` / `import { type X }`, whatever the importer then does with it;
  a namespace import read as `ns.X` or `ns['X']` outside a type, or used whole
  (`f(ns)`, `ns[key]`); a dynamic `import()`. Re-exports are followed, so a
  barrel is transparent.
- **an entry point** — a file the package publishes (see
  [Entry points](#entry-points)) — that re-exports it as a value, directly or
  through any chain of `export { … } from` / `export * from`.

The rule reports; there is no fix, since writing the type out is not
mechanical.

#### Type information

Whether another file reads an exported codec is a question about the whole
TypeScript project, so the rule answers it from the program a file is linted
with. Turn type information on for it to check exported codecs at all:

```ts
// eslint.config.mts
import { eslintPluginTsFortress } from 'eslint-plugin-ts-fortress';

export default [
    eslintPluginTsFortress.configs.recommended,
    {
        languageOptions: {
            parserOptions: {
                projectService: true,
                tsconfigRootDir: import.meta.dirname,
            },
        },
    },
];
```

Without it, a codec that is not exported is still checked — that needs nothing
but its own file — and an exported one is left alone.

The rule sees the files of that program and nothing else. An importer counts
only if the `tsconfig.json` linting the codec's file includes it, so tests under
a separate project import nothing as far as the rule can tell, and another
package that imports the codec reaches it through an entry point.

#### Entry points

A codec the package publishes is public API, whoever uses it. The entry points
are read from the `package.json` nearest to the file — `exports`, every subpath
and condition of it, and the legacy `main`, `module`, `types` and `typings`
fields — and traced back to source: a target that is a file of the project is
taken as it is, and an output such as `./dist/index.mjs` becomes the source it
was built from, `src/index.mts` (the project's `outDir` and `rootDir` are used
when set; otherwise a leading `dist`, `lib`, `build`, `out`, `esm` or `cjs`
directory becomes `src`). The conditions of one subpath describe one module, so
a subpath counts as traced when any of its targets is, and a `types` file a
build writes on its own does not need a source. A package that publishes nothing
— an application — has no entry points.

When some subpath cannot be traced back to a file of the project, what the
package publishes is not known, and the rule leaves its exported codecs alone
rather than report public API. Name the entry points yourself for such a layout:

```ts
'ts-fortress/no-type-only-codec': [
  'error',
  { entryPoints: [path.resolve(import.meta.dirname, 'src/public-api.mts')] },
],
```

- `entryPoints` (default: read from `package.json`) — the files whose exports
  are public API, replacing what `package.json` says. Relative paths resolve
  against the directory ESLint runs in, so pass absolute ones, as above.

## License

[Apache-2.0](https://github.com/noshiro-pf/mono/blob/main/libs/eslint-plugin-ts-fortress/LICENSE)
