diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml index fcc7c56..86e4dd4 100644 --- a/.github/workflows/website.yml +++ b/.github/workflows/website.yml @@ -7,12 +7,12 @@ on: - main paths: - website/** - - RULES.md + - docs/user-guide/** - README.md pull_request: paths: - website/** - - RULES.md + - docs/user-guide/** - README.md concurrency: diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a70360..7a26733 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ First stable release. -- 30 rules for Effect code, grouped by topic in [`RULES.md`](RULES.md): error channel, tagged values, services and Layers, runtime and entry point, design and boundaries, effectful functions, code shape, Schema, config and secrets. Three are absorbed from [`dmmulroy/anti-slop`](https://github.com/dmmulroy/anti-slop). +- 30 rules for Effect code, grouped by topic in [`docs/user-guide/rules.md`](docs/user-guide/rules.md): error channel, tagged values, services and Layers, runtime and entry point, design and boundaries, effectful functions, code shape, Schema, config and secrets. Three are absorbed from [`dmmulroy/anti-slop`](https://github.com/dmmulroy/anti-slop). - An `all` preset that enables every rule at `warn`, for `oxlint.config.ts` and `.oxlintrc.json`. - Shared settings under `settings["dl-effect"]`: `entryFiles`, `testFiles`, `discriminants`. - Written for Effect 4; rules also recognize the Effect 3 name of the same API. diff --git a/CLAUDE.md b/CLAUDE.md index a649f28..c3b946a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,9 +4,11 @@ After any change, run `pnpm format && pnpm build-and-pack` and fix what it repor Do not modify the logic or messages of `rules/anti-slop-*`: they are absorbed from `dmmulroy/anti-slop` and must stay resyncable. When a dl-effect rule covers the same case more strongly, retire the anti-slop rule instead. -When adding or editing a section of `RULES.md`, follow [`docs/rules-catalog-style.md`](docs/rules-catalog-style.md). +The rule catalog is one file per rule, `docs/user-guide/rules/.md`, listed in the rules index, `docs/user-guide/rules.md`. When adding or editing a rule file, follow [`docs/rules-catalog-style.md`](docs/rules-catalog-style.md). -The website (`website/`) parses `RULES.md` and `README.md` in its content module (`website/src/site-content/`) and fails its build when a rule section breaks the catalog template or a link resolves to no page: a change to the template or to the structure of `RULES.md` or `README.md` must update the content module and its tests (`cd website && pnpm test`). Each `##` section of `README.md` becomes a site page except Development, which addresses maintainers only. +The website (`website/`) is built from `docs/user-guide/` by its content module (`website/src/site-content/`). Each `docs/user-guide/` file is a page, titled and ordered by its frontmatter; `docs/user-guide/README.md` is the guide index and the landing page, `docs/user-guide/rules.md` the Rules overview, whose links order the rule pages; each rule file is a rule page in the group of its frontmatter. Links between guide files are relative `.md` paths. The build fails when a guide file's frontmatter is invalid, a rule file breaks the catalog template or is missing from the rules index, or a link resolves to no page: a change to the template, to the frontmatter or to the structure of the rules index must update the content module and its tests (`cd website && pnpm test`). + +The README is the essential guide: introduction, installation, the happy path and the warnings that matter before adopting the plugin. It links to the website guide with absolute URLs and does not repeat it; anything else goes in `docs/user-guide/`. Maintainer docs go in `CONTRIBUTING.md`, which has no site page. ## Agent skills diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..905087f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,15 @@ +# Contributing + +## Development + +- `pnpm format`: formats with oxfmt; the only script that rewrites sources. +- `pnpm check`: format check, typecheck, lint and tests, writing nothing. The tests are the `RuleTester`s from `oxlint/plugins-dev` with `node --test`, plus a check that the rule catalog, `docs/user-guide/rules/`, has exactly one file per rule of the plugin. +- `pnpm build`: compiles to `dist/` and generates `dist/presets/all.json` from `presets/all.ts` (the rule list comes from the plugin). +- `pnpm pack:check`: checks the built preset, then the tarball `npm pack` would publish: only the files in `files`, no local absolute paths, `publint --strict`. +- `pnpm smoke-test`: installs the tarball in `smoke-fixture/` with pnpm and checks the diagnostics of oxlint with each config form: `oxlint.config.ts` and `.oxlintrc.json` with the preset, `.oxlintrc.json` with the plugin by package name. +- `pnpm build-and-pack`: `check`, `build`, `pack:check` and `smoke-test`; run it after every change. +- `pnpm release `: from a clean `main` equal to `origin/main`, runs `build-and-pack`, bumps with `npm version --preid rc` (`prerelease` for the next rc, `x.y.z` for a stable), publishes, then pushes the commit and the tag. A prerelease is `next`, and also `latest` until the first stable version; a stable version is `latest` and `next`. A failed publish undoes the bump. Without ``, prints the version in `package.json` and the npm dist-tags. +- `pnpm build:w`: reruns `pnpm build`, preset included, on every change to `index.ts`, `rules/`, `presets/`, `shared/` or `tsconfig.build.json`; a failed build waits for the next change. +- `pnpm consumer:link `: after `pnpm build`, replaces the pnpm symlinks of the plugin in every workspace package of `` with links to the checkout, so the consumer's own lint runs the checkout's rules; no tracked file of the consumer changes. `pnpm consumer:unlink ` restores them with `pnpm install --frozen-lockfile`, as does any `pnpm install` in the consumer. + +A new rule must be registered in `index.ts`, documented in its rule file, `docs/user-guide/rules/.md` (see [`docs/rules-catalog-style.md`](docs/rules-catalog-style.md)), and linked from its topic in the rules index, `docs/user-guide/rules.md`; `pnpm build` adds it to the preset. diff --git a/README.md b/README.md index e7d3ecf..a4e3dc8 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ An oxlint plugin that enforces a catalog of patterns for Effect 4 code. -The rules are written and tested against Effect 4. Where an Effect 3 API has the same intent, the rules recognize its v3 name too: each rule's Trigger in [`RULES.md`](RULES.md) names them. +The rules are written and tested against Effect 4. Where an Effect 3 API has the same intent, the rules recognize its v3 name too: each rule's Trigger names them. The [Rules overview](https://doubleloop-io.github.io/oxlint-plugin-effect/rules-overview/) lists every rule. -It complements the type-aware rules of [`@effect/tsgo`](#alongside-effecttsgo): it does not need them, and it checks what they do not. +It complements the type-aware rules of [`@effect/tsgo`](https://doubleloop-io.github.io/oxlint-plugin-effect/alongside-effect-tsgo/): it does not need them, and it checks what they do not. ## Installation @@ -12,9 +12,9 @@ It complements the type-aware rules of [`@effect/tsgo`](#alongside-effecttsgo): pnpm add -D @doubleloop-io/oxlint-plugin-effect oxlint ``` -Requires Node `^22.20.0 || >=24.8.0` and oxlint `^1.82.0`. +Requires Node `^22.20.0 || >=24.8.0` and oxlint `^1.82.0`. What a release may change and which oxlint versions are supported: [Versioning](https://doubleloop-io.github.io/oxlint-plugin-effect/versioning/). -## Configuration +## Usage Extend the `all` preset. Prefer `oxlint.config.ts`, where `extends` takes config objects and the preset is imported by package name: @@ -33,205 +33,20 @@ With `.oxlintrc.json`, `extends` takes file paths only, so the preset is reached } ``` -`all` enables every rule at `warn`, so adopting it never breaks a build: look at the warnings first, then raise to `error` the rules you want to enforce. A `recommended` preset with reasoned severities will come from measurements on real codebases. +`all` enables every rule at `warn`, so adopting it never breaks a build: look at the warnings first, then raise to `error` the rules you want to enforce. -To pick rules without the preset, load the plugin by package name and list the rules: +**Set `entryFiles` before reading the warnings** on a layout that is not a Node CLI, such as Next.js or a monorepo. Its default, `**/main.ts`, `**/cli.ts`, `**/bin/**`, decides which files may run Effects and import adapters, so on another layout it turns correct code into warnings. How to set it: [Shared settings](https://doubleloop-io.github.io/oxlint-plugin-effect/shared-settings/#setting-a-value). -```json -{ - "jsPlugins": ["@doubleloop-io/oxlint-plugin-effect"], - "rules": { - "dl-effect/no-effect-promise": "error", - "dl-effect/try-object-form": "error" - } -} -``` - -### Configuration options - -Three settings describe your project, not a rule, so they are declared once under `settings["dl-effect"]` and every rule that uses them reads them from there. Their defaults fit a Node CLI; on another layout (Next.js, a monorepo) set them before reading the warnings. - -- `entryFiles`: the files allowed to run Effects and import adapters. Default `**/main.ts`, `**/cli.ts`, `**/bin/**`. -- `testFiles`: the test files, exempt from the rules that tests legitimately break and the only files `prefer-effect-vitest` checks. Default `**/*.test.*`, `**/*.spec.*`, `**/__tests__/**`, `**/test/**`, `**/tests/**`. -- `discriminants`: the fields that discriminate a closed union. Default `_tag`; add the ones your unions use, such as `type` or `kind`. - -The rules that use each one are listed in [Shared settings](RULES.md#shared-settings). Set one only where its default does not fit: it **replaces** the default instead of extending it. An unknown key or a value that is not an array of strings stops the lint with an error, so a typo is never silently ignored. - -```ts -import dlEffectAll from "@doubleloop-io/oxlint-plugin-effect/presets/all" -import { defineConfig } from "oxlint" - -export default defineConfig({ - extends: [dlEffectAll], - settings: { - "dl-effect": { entryFiles: ["apps/web/src/app/**/route.ts", "apps/web/src/runtime.ts"] }, - }, -}) -``` - -```json -{ - "extends": ["./node_modules/@doubleloop-io/oxlint-plugin-effect/dist/presets/all.json"], - "settings": { - "dl-effect": { "entryFiles": ["apps/web/src/app/**/route.ts", "apps/web/src/runtime.ts"] } - } -} -``` - -The package exports the defaults as `defaultEntryFiles`, `defaultTestFiles` and `defaultDiscriminants`: spread them to extend a default (`testFiles: [...defaultTestFiles, "e2e/**"]`). - -Settings belong to the config that lints: oxlint does not inherit them from a preset in `extends`, and rejects them in `overrides`. For a value that differs by group of files, use `overrides` on the rules instead. - -The other options and every default are in [Default configuration](#default-configuration). - -### Alongside `@effect/tsgo` - -[`@effect/tsgo`](https://github.com/Effect-TS/tsgo) is the official Effect language service on top of the TypeScript Go compiler; its `effecttsgo` oxlint presets add more than 100 type-aware rules. This plugin does not need it, and its rules target what those presets do not check, so the two complement each other. To use both, follow its [Oxlint Setup guide](https://github.com/Effect-TS/tsgo/blob/main/docs/README.md) and put its preset in `extends` **before** `all`: - -```ts -import dlEffectAll from "@doubleloop-io/oxlint-plugin-effect/presets/all" -import { recommended as effectTsgoRecommended } from "@effect/tsgo/oxlint-presets" -import { defineConfig } from "oxlint" - -export default defineConfig({ extends: [effectTsgoRecommended, dlEffectAll] }) -``` - -```json -{ - "extends": [ - "./node_modules/@effect/tsgo/oxlint-presets/recommended.json", - "./node_modules/@doubleloop-io/oxlint-plugin-effect/dist/presets/all.json" - ] -} -``` - -## Rules - -What each rule reports and why is in [`RULES.md`](RULES.md). Report false positives and missed cases in the [GitHub issues](https://github.com/doubleloop-io/oxlint-plugin-effect/issues). - -| Topic | Rules | -| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Error channel | [`no-throw-or-primitive-failure`](RULES.md#no-throw-or-primitive-failure), [`try-object-form`](RULES.md#try-object-form), [`no-effect-promise`](RULES.md#no-effect-promise), [`no-parameterless-catch-all`](RULES.md#no-parameterless-catch-all), [`split-success-path-from-error-handling`](RULES.md#split-success-path-from-error-handling), [`anti-slop-no-manual-effect-error-tag`](RULES.md#anti-slop-no-manual-effect-error-tag) | -| Tagged values | [`no-manual-discriminant-comparison`](RULES.md#no-manual-discriminant-comparison), [`no-manual-discriminant-construction`](RULES.md#no-manual-discriminant-construction) | -| Services & Layers | [`service-port-shape-only`](RULES.md#service-port-shape-only), [`service-key-matches-name`](RULES.md#service-key-matches-name), [`service-built-with-of`](RULES.md#service-built-with-of), [`provide-named-layer`](RULES.md#provide-named-layer), [`no-provide-on-definition`](RULES.md#no-provide-on-definition), [`anti-slop-no-service-constructor-imports`](RULES.md#anti-slop-no-service-constructor-imports) | -| Runtime & entrypoint | [`run-only-in-runner`](RULES.md#run-only-in-runner), [`prefer-effect-vitest`](RULES.md#prefer-effect-vitest), [`all-errors-handled-at-boundary`](RULES.md#all-errors-handled-at-boundary) | -| Design & boundaries | [`adapter-import-boundary`](RULES.md#adapter-import-boundary), [`no-transport-types-in-generator`](RULES.md#no-transport-types-in-generator) | -| Effectful functions | [`prefer-effect-fn`](RULES.md#prefer-effect-fn), [`untraced-recursion`](RULES.md#untraced-recursion), [`single-style-per-function`](RULES.md#single-style-per-function) | -| Code shape | [`no-nested-match`](RULES.md#no-nested-match), [`no-yielded-match`](RULES.md#no-yielded-match), [`no-inline-yield-star`](RULES.md#no-inline-yield-star), [`no-effect-return-type`](RULES.md#no-effect-return-type), [`no-asymmetric-match-handlers`](RULES.md#no-asymmetric-match-handlers), [`anti-slop-prefer-effect-match`](RULES.md#anti-slop-prefer-effect-match) | -| Schema | [`exported-schema-identifier`](RULES.md#exported-schema-identifier), [`no-inline-schema-codec`](RULES.md#no-inline-schema-codec) | -| Config & secrets | [`redacted-secret-names`](RULES.md#redacted-secret-names) | - -### Absorbed from anti-slop - -Some rules come from the Effect rules of [`dmmulroy/anti-slop`](https://github.com/dmmulroy/anti-slop), MIT-licensed: see [`LICENSE.anti-slop`](LICENSE.anti-slop). - -| Status | Rules | -| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Imported | [`anti-slop-no-manual-effect-error-tag`](RULES.md#anti-slop-no-manual-effect-error-tag), [`anti-slop-no-service-constructor-imports`](RULES.md#anti-slop-no-service-constructor-imports), [`anti-slop-prefer-effect-match`](RULES.md#anti-slop-prefer-effect-match) | -| Superseded | `no-manual-tag-comparison` → [`no-manual-discriminant-comparison`](RULES.md#no-manual-discriminant-comparison), `no-manual-tagged-construction` → [`no-manual-discriminant-construction`](RULES.md#no-manual-discriminant-construction) | - -## Default configuration - -`all` is equivalent to the config below, with every setting and option spelled out at its default. Both **replace** the defaults instead of extending them: see [Shared settings](RULES.md#shared-settings). - -```ts -import { defineConfig } from "oxlint" - -// Constructors that must not appear inside an Effect generator: the conversion to the -// transport belongs in the second argument of Effect.fn. Add your own transport DTOs. -const transportTypes = ["Response", "NextResponse"] - -// Schema fields holding a secret: a field matches an entry or ends with it capitalized -// (`password` matches `dbPassword`). No generic `token`: `nextPageToken` is not a secret. -const secretFields = ["password", "secret", "apiKey", "accessToken", "refreshToken", "idToken"] - -export default defineConfig({ - jsPlugins: ["@doubleloop-io/oxlint-plugin-effect"], - settings: { - "dl-effect": { - // Files allowed to run Effects (Effect.run*, runMain, ManagedRuntime.make) and to - // import adapters. `index.ts` is left out on purpose: as a barrel it would let - // adapters leak through re-exports. - entryFiles: ["**/main.ts", "**/cli.ts", "**/bin/**"], - // Files exempt from the rules that tests legitimately break. Helper directories such - // as `src/testing/` are support code, not tests, so they are not matched. - testFiles: [ - "**/*.test.*", - "**/*.spec.*", - "**/__tests__/**", - "**/test/**", - "**/tests/**", - ], - // Fields that discriminate a closed union, compared or switched on only through an - // exhaustive match and set only by a constructor. Add the ones your unions use, such - // as `type` or `kind`. - discriminants: ["_tag"], - }, - }, - // Every rule at `warn`, to measure noise without blocking. - rules: { - // Error channel - "dl-effect/no-throw-or-primitive-failure": "warn", - "dl-effect/try-object-form": "warn", - "dl-effect/no-effect-promise": "warn", - "dl-effect/no-parameterless-catch-all": "warn", - "dl-effect/split-success-path-from-error-handling": "warn", - "dl-effect/anti-slop-no-manual-effect-error-tag": "warn", - // Tagged values - "dl-effect/no-manual-discriminant-comparison": "warn", - "dl-effect/no-manual-discriminant-construction": "warn", - // Services & Layers - "dl-effect/service-port-shape-only": "warn", - "dl-effect/service-key-matches-name": "warn", - "dl-effect/service-built-with-of": "warn", - "dl-effect/provide-named-layer": "warn", - "dl-effect/no-provide-on-definition": "warn", - "dl-effect/anti-slop-no-service-constructor-imports": "warn", - // Runtime & entrypoint - "dl-effect/run-only-in-runner": "warn", - "dl-effect/prefer-effect-vitest": "warn", - "dl-effect/all-errors-handled-at-boundary": "warn", - // Design & boundaries - "dl-effect/adapter-import-boundary": "warn", - "dl-effect/no-transport-types-in-generator": ["warn", { transportTypes }], - // Effectful functions - "dl-effect/prefer-effect-fn": "warn", - "dl-effect/untraced-recursion": "warn", - "dl-effect/single-style-per-function": "warn", - // Code shape - "dl-effect/no-nested-match": "warn", - "dl-effect/no-yielded-match": "warn", - "dl-effect/no-inline-yield-star": "warn", - "dl-effect/no-effect-return-type": ["warn", { checkExported: false }], - "dl-effect/no-asymmetric-match-handlers": "warn", - "dl-effect/anti-slop-prefer-effect-match": "warn", - // Schema - "dl-effect/exported-schema-identifier": "warn", - "dl-effect/no-inline-schema-codec": "warn", - // Config & secrets - "dl-effect/redacted-secret-names": ["warn", { secretFields }], - }, -}) -``` - -To change a setting, declare it in `settings`; to change a rule option, extend `all` and override only that rule. - -## Versioning - -Versions are `0.x`: any minor release may add, remove or change rules, options, settings and messages. - -Supported oxlint is the `peerDependencies` range, `^1.82.0`; CI tests the tarball against `1.82.0`. oxlint's JS plugin API is still experimental, so a newer oxlint minor may break the plugin before the range is narrowed. +## Documentation -## Development +The guide is on the [website](https://doubleloop-io.github.io/oxlint-plugin-effect/): -- `pnpm format`: formats with oxfmt; the only script that rewrites sources. -- `pnpm check`: format check, typecheck, lint and tests, writing nothing. The tests are the `RuleTester`s from `oxlint/plugins-dev` with `node --test`, plus an alignment check of `RULES.md` with one section per rule. -- `pnpm build`: compiles to `dist/` and generates `dist/presets/all.json` from `presets/all.ts` (the rule list comes from the plugin). -- `pnpm pack:check`: checks the built preset, then the tarball `npm pack` would publish: only the files in `files`, no local absolute paths, `publint --strict`. -- `pnpm smoke-test`: installs the tarball in `smoke-fixture/` with pnpm and checks the diagnostics of oxlint with each config form: `oxlint.config.ts` and `.oxlintrc.json` with the preset, `.oxlintrc.json` with the plugin by package name. -- `pnpm build-and-pack`: `check`, `build`, `pack:check` and `smoke-test`; run it after every change. -- `pnpm release `: from a clean `main` equal to `origin/main`, runs `build-and-pack`, bumps with `npm version --preid rc` (`prerelease` for the next rc, `x.y.z` for a stable), publishes, then pushes the commit and the tag. A prerelease is `next`, and also `latest` until the first stable version; a stable version is `latest` and `next`. A failed publish undoes the bump. Without ``, prints the version in `package.json` and the npm dist-tags. -- `pnpm build:w`: reruns `pnpm build`, preset included, on every change to `index.ts`, `rules/`, `presets/`, `shared/` or `tsconfig.build.json`; a failed build waits for the next change. -- `pnpm consumer:link `: after `pnpm build`, replaces the pnpm symlinks of the plugin in every workspace package of `` with links to the checkout, so the consumer's own lint runs the checkout's rules; no tracked file of the consumer changes. `pnpm consumer:unlink ` restores them with `pnpm install --frozen-lockfile`, as does any `pnpm install` in the consumer. +- [Configuration](https://doubleloop-io.github.io/oxlint-plugin-effect/configuration/): the `all` preset and picking rules. +- [Shared settings](https://doubleloop-io.github.io/oxlint-plugin-effect/shared-settings/): the settings that describe your project, their defaults and the rules that use them. +- [Default configuration](https://doubleloop-io.github.io/oxlint-plugin-effect/default-configuration/): `all` with every setting and option spelled out. +- [Alongside `@effect/tsgo`](https://doubleloop-io.github.io/oxlint-plugin-effect/alongside-effect-tsgo/): combining its presets with this one. +- [Rules overview](https://doubleloop-io.github.io/oxlint-plugin-effect/rules-overview/): every rule, grouped by topic. +- [Versioning](https://doubleloop-io.github.io/oxlint-plugin-effect/versioning/): what a release may change. +- [Troubleshooting](https://doubleloop-io.github.io/oxlint-plugin-effect/troubleshooting/): the problems most often hit when adopting the plugin. -A new rule must be registered in `index.ts` and documented in `RULES.md` under a `` ### `rule-name` `` heading; `pnpm build` adds it to the preset. +Coding agents: the same pages ship in the package under `docs/user-guide/`, starting from `docs/user-guide/README.md`. diff --git a/RULES.md b/RULES.md deleted file mode 100644 index f7ca236..0000000 --- a/RULES.md +++ /dev/null @@ -1,1056 +0,0 @@ -# `@doubleloop-io/oxlint-plugin-effect` rules - -The plugin's 31 rules. - -## Rules index - -| Group | Rule | -| --------------------------------------------------- | --------------------------------------------------------------------------------------- | -| [Error channel](#error-channel) | [`no-throw-or-primitive-failure`](#no-throw-or-primitive-failure) | -| | [`try-object-form`](#try-object-form) | -| | [`no-effect-promise`](#no-effect-promise) | -| | [`no-parameterless-catch-all`](#no-parameterless-catch-all) | -| | [`split-success-path-from-error-handling`](#split-success-path-from-error-handling) | -| | [`anti-slop-no-manual-effect-error-tag`](#anti-slop-no-manual-effect-error-tag) | -| [Tagged values](#tagged-values) | [`no-manual-discriminant-comparison`](#no-manual-discriminant-comparison) | -| | [`no-manual-discriminant-construction`](#no-manual-discriminant-construction) | -| [Services and Layers](#services-and-layers) | [`service-port-shape-only`](#service-port-shape-only) | -| | [`service-key-matches-name`](#service-key-matches-name) | -| | [`service-built-with-of`](#service-built-with-of) | -| | [`provide-named-layer`](#provide-named-layer) | -| | [`no-provide-on-definition`](#no-provide-on-definition) | -| | [`anti-slop-no-service-constructor-imports`](#anti-slop-no-service-constructor-imports) | -| [Runtime and entry point](#runtime-and-entry-point) | [`run-only-in-runner`](#run-only-in-runner) | -| | [`prefer-effect-vitest`](#prefer-effect-vitest) | -| | [`all-errors-handled-at-boundary`](#all-errors-handled-at-boundary) | -| [Design and boundaries](#design-and-boundaries) | [`adapter-import-boundary`](#adapter-import-boundary) | -| | [`no-transport-types-in-generator`](#no-transport-types-in-generator) | -| [Effectful functions](#effectful-functions) | [`prefer-effect-fn`](#prefer-effect-fn) | -| | [`untraced-recursion`](#untraced-recursion) | -| | [`single-style-per-function`](#single-style-per-function) | -| [Code shape](#code-shape) | [`no-nested-match`](#no-nested-match) | -| | [`no-yielded-match`](#no-yielded-match) | -| | [`no-inline-yield-star`](#no-inline-yield-star) | -| | [`no-effect-return-type`](#no-effect-return-type) | -| | [`no-asymmetric-match-handlers`](#no-asymmetric-match-handlers) | -| | [`anti-slop-prefer-effect-match`](#anti-slop-prefer-effect-match) | -| [Schema](#schema) | [`exported-schema-identifier`](#exported-schema-identifier) | -| | [`no-inline-schema-codec`](#no-inline-schema-codec) | -| [Config and secrets](#config-and-secrets) | [`redacted-secret-names`](#redacted-secret-names) | - -The `all` preset enables them all at `warn`. - -## Common limits - -- **Syntax only**: no rule uses type information. Only two rules look past the file: [`adapter-import-boundary`](#adapter-import-boundary), to find which directories are adapters, and [`prefer-effect-vitest`](#prefer-effect-vitest), to find whether `@effect/vitest` is installed. -- **Literal names**: `Effect.gen` is recognized, `import { Effect as E }` or `import * as L from "effect/Layer"` slip through. On code that uses aliases, silence is not compliance. -- **Effect 4**: the rules are written against v4. Where a v3 API has the same intent, they recognize its v3 name too (`catchAll`, `Either`, `Context.Tag`, `Config.redacted`, …), and the Trigger names it. - -## Shared settings - -What describes the project rather than a rule is declared once, under `settings["dl-effect"]` in the oxlint config, and read by every rule that needs it. A value **replaces** the default (it does not extend it). An unknown key or a value that is not an array of strings stops the lint with an error. File globs are matched against the path relative to oxlint's working directory, with `/` on every platform. - -- **`entryFiles`** - - used by: - - [`run-only-in-runner`](#run-only-in-runner) - - [`adapter-import-boundary`](#adapter-import-boundary) - - default: `**/main.ts`, `**/cli.ts`, `**/bin/**`. `index.ts` is excluded on purpose: it is usually a barrel, and exempting it would let adapters reach the rest of the application through re-exports. -- **`testFiles`** - - used by: - - [`run-only-in-runner`](#run-only-in-runner), [`adapter-import-boundary`](#adapter-import-boundary), [`no-effect-promise`](#no-effect-promise), [`provide-named-layer`](#provide-named-layer), [`no-provide-on-definition`](#no-provide-on-definition), [`split-success-path-from-error-handling`](#split-success-path-from-error-handling), [`all-errors-handled-at-boundary`](#all-errors-handled-at-boundary), [`anti-slop-no-service-constructor-imports`](#anti-slop-no-service-constructor-imports): skip test files - - [`no-throw-or-primitive-failure`](#no-throw-or-primitive-failure): skips only primitive failures there - - [`single-style-per-function`](#single-style-per-function): treats their helpers like tests - - [`prefer-effect-vitest`](#prefer-effect-vitest): checks only them - - default: `**/*.test.*`, `**/*.spec.*`, `**/__tests__/**`, `**/test/**`, `**/tests/**`. A helper directory such as `src/testing/` does not count as tests: it is support code. -- **`discriminants`** - - used by: - - [`no-manual-discriminant-comparison`](#no-manual-discriminant-comparison) - - [`no-manual-discriminant-construction`](#no-manual-discriminant-construction) - - default: `_tag`. Add the fields your unions discriminate on (`type`, `kind`). - -The file defaults come from a Node CLI. On another layout (Next.js, a monorepo) they must be reconfigured before reading the warnings: - -```ts -export default defineConfig({ - extends: [dlEffectAll], - settings: { - "dl-effect": { entryFiles: ["apps/web/src/app/**/route.ts", "apps/web/src/runtime.ts"] }, - }, -}) -``` - -Settings are not inherited from a preset in `extends` and cannot go in `overrides`: for a value that differs by group of files, override the rules instead. - -## Error channel - -### `no-throw-or-primitive-failure` - -[↑ rules index](#rules-index) - -**Intent**: an expected failure is a tagged error, never a thrown or primitive value. - -```ts -// no -Effect.gen(function* () { - if (tab === undefined) throw new Error("tab not found") -}) -Effect.fail("tab not found") - -// yes -export class SheetTabNotFoundError extends Schema.TaggedError()( - "SheetTabNotFoundError", - { spreadsheetId: Schema.String, message: Schema.String }, -) {} - -Effect.fail(new SheetTabNotFoundError({ spreadsheetId, message: "tab not found" })) -``` - -**Trigger**: a `throw` directly inside a generator passed to `Effect.gen`/`Effect.fn`; `Effect.fail` with a literal or a template. - -**Exemptions and blind spots**: `Effect.fail` with a literal in test files, where a synthetic failure feeds code generic over the error; a `throw` in a test generator is still reported. A `throw` inside a nested callback. `Effect.fail(new Error(…))` and `class X extends Error`: see `global-error-in-effect-failure` and `extends-native-error` (effecttsgo). - -**Why**: the typed error channel discriminates only on tags. A `throw` in the generator becomes a defect, outside the error channel. - -**Options**: - -- `testFiles`: shared setting, see [Shared settings](#shared-settings). - -**Fix**: none - -### `try-object-form` - -[↑ rules index](#rules-index) - -**Intent**: `Effect.try` and `Effect.tryPromise` take `{ try, catch }`, with `catch` producing a tagged error. - -```ts -// no -Effect.tryPromise(() => api.spreadsheets.get({ spreadsheetId })) - -// yes -Effect.tryPromise({ - try: () => api.spreadsheets.get({ spreadsheetId }), - catch: toSheetError(spreadsheetId), -}) -``` - -**Trigger**: `Effect.try` and `Effect.tryPromise` whose argument is not an object literal. - -**Exemptions and blind spots**: an options object held in a variable is reported too. - -**Why**: the thunk form types the error as `Cause.UnknownError` (`UnknownException` in v3), which no caller can handle by tag. - -**Options**: none - -**Fix**: none - -### `no-effect-promise` - -[↑ rules index](#rules-index) - -**Intent**: a promise that can reject is lifted with [`Effect.tryPromise`](#try-object-form), not `Effect.promise`. - -```ts -// no -Effect.promise(() => client.connect()) - -// yes -Effect.tryPromise({ try: () => client.connect(), catch: toConnectionError }) -``` - -**Trigger**: `Effect.promise` outside the release step of `acquireRelease`, `acquireUseRelease` and `addFinalizer`. - -**Exemptions and blind spots**: the release step, where a promise that cannot reject is the normal case. Test files, where a rejection during setup is a broken test and the defect fails it with the cause. Elsewhere, a promise that truly cannot reject must be suppressed by hand. - -**Why**: `Effect.promise` turns a rejection into a defect. - -**Options**: - -- `testFiles`: shared setting, see [Shared settings](#shared-settings). - -**Fix**: none - -### `no-parameterless-catch-all` - -[↑ rules index](#rules-index) - -**Intent**: errors are caught by tag; a fallback that ignores the error is spelled `orElseSucceed`/`orElse`, never a catch-all with an ignored parameter. - -```ts -// no -Effect.catch(() => Effect.succeed(fallback)) - -// yes -Effect.catchTag("AgentTimeout", () => Effect.succeed(skip)) -Effect.catchTag(["ParseError", "ReservedPortError"], () => Effect.succeed(3000)) - -// yes: every failure truly means the same fallback -Effect.orElseSucceed(() => fallback) -``` - -**Trigger**: `Effect.catch`, `catchAll`, `catchCause` and `catchEager` with a parameterless handler. - -**Exemptions and blind spots**: a catch-all that discriminates on `_tag` by hand: see [`anti-slop-no-manual-effect-error-tag`](#anti-slop-no-manual-effect-error-tag), and `catch-all-to-map-error`, `catch-all-tag-dispatch-to-catch-tag` and `catch-to-ignore` (effecttsgo). - -**Why**: a catch-all that ignores its parameter also swallows the errors added later, which `catchTag` would leave visible in the type. - -**Options**: none - -**Fix**: none - -### `split-success-path-from-error-handling` - -[↑ rules index](#rules-index) - -**Intent**: the generator holds only the happy path; error handling lives in the second argument of `Effect.fn`. - -```ts -// no -function* () { - const x = yield* fetchThing.pipe(Effect.catchTag("NotFound", () => Effect.succeed(fallback))) -} - -// yes: naming the error or giving an alternative is not handling -function* () { - const x = yield* fetchThing.pipe(Effect.orElseSucceed(() => fallback)) - const y = yield* decode(raw).pipe(Effect.mapError((error) => new BadRequest({ message: error.message }))) -} - -// yes: translation in the second argument, which also receives the original arguments -const createEvent = Effect.fn("events.create")( - function* (request: Request) { /* success only */ }, - (effect, request) => effect.pipe(Effect.catchTags({ BadRequest: (e) => refused(400, e.message) })), -) -``` - -**Trigger**: inside a generator passed to `Effect.gen`/`Effect.fn`, callbacks passed to `Effect.*` combinators included, calls to `Effect.catch*` (`catch`, `catchAll`, `catchTag`, `catchTags`, `catchIf`, `catchCause`, `catchDefect`, `catchReason`, …), `either`, `result`, `exit`, `match*` and `sandbox`. - -**Exemptions and blind spots**: pipeables of a nested `Effect.fn`. Handlers inside the callback of an iteration (`forEach`, `filter`, `reduce`, `partition`, `validate`, `findFirst`, …): they handle each element on its own, and in the pipeables the first failure would stop the rest. Functions the generator only defines, such as an `HttpApiBuilder` handler or a service method: they are programs of their own. Test files, where the failure is the outcome under observation (`yield* Effect.result(op)` then `expect`). A `catch`, `catchTag`, `catchTags`, `catchIf` or `catchFilter` whose handlers only die (`Effect.die` passed directly or as the sole return): it is a selective `orDie`, declaring the case untracked rather than handling it; a die behind a wrapper or a condition is still reported. A `.pipe(Effect.catch…)` appended to an `Effect.gen` escapes; [`prefer-effect-fn`](#prefer-effect-fn) closes that gap. - -**Why**: translation becomes a single exhaustive point instead of catches scattered along the flow. - -**Options**: - -- `testFiles`: shared setting, see [Shared settings](#shared-settings). - -**Fix**: none - -### `anti-slop-no-manual-effect-error-tag` - -[↑ rules index](#rules-index) - -**Intent**: a catch handler does not discriminate errors by `_tag`; `catchTag` and `catchReason` do. - -```ts -// no -program.pipe(Effect.catch((error) => (error._tag === "NotFound" ? recover : Effect.fail(error)))) - -// yes -program.pipe(Effect.catchTag("NotFound", () => recover)) -``` - -**Trigger**: an equality comparison between `_tag` (or `reason._tag`) and a string literal, or a `switch` on `_tag`, whose nearest enclosing function is a handler passed to `Effect.catch`, `catchAll` or `catchIf`. On `reason._tag` the message proposes `Effect.catchReason(s)`. - -**Exemptions and blind spots**: handlers of other combinators (`catchTag`, `catchCause`, `mapError`), and `_tag` checks in a function nested inside the handler. Outside these handlers the same checks belong to [`no-manual-discriminant-comparison`](#no-manual-discriminant-comparison): the two never fire on the same node. - -**Why**: a hand-written dispatch keeps the caught errors in the type even when handled, and silently misses tags added later. - -**Options**: none - -**Fix**: none - -## Tagged values - -### `no-manual-discriminant-comparison` - -[↑ rules index](#rules-index) - -**Intent**: branching on a union's discriminant goes through an exhaustive match, never through comparisons or `switch`. - -```ts -// no -switch (event._tag) { - case "Created": - return onCreated(event) - case "Deleted": - return onDeleted(event) -} - -// yes -Match.value(event).pipe(Match.tagsExhaustive({ Created: onCreated, Deleted: onDeleted })) - -// yes, with `discriminants: ["_tag", "type"]` -Match.value(payment).pipe( - Match.discriminatorsExhaustive("type")({ card: fromCard, transfer: fromTransfer }), -) -``` - -**Trigger**: an equality comparison between a discriminant (also `["type"]`) and a string literal, or a `switch` on a discriminant. The discriminants are the names in `discriminants`. - -**Exemptions and blind spots**: comparisons against a variable rather than a literal. On `_tag`, the handlers covered by [`anti-slop-no-manual-effect-error-tag`](#anti-slop-no-manual-effect-error-tag): the two never fire on the same node. Guard clauses such as `if (x.type === "a") return …` fire too; on `_tag` use `Predicate.isTagged`. A `_tag` compared with a variant of Effect's own types (`Success`/`Failure` of `Result` and `Exit`, `Left`/`Right`, `Some`/`None`) is reported with their refinement as the remedy, such as `Result.isFailure`: those types cannot gain a variant; a `switch` is reported as usual. An exhaustive ts-pattern match is an equally valid remedy. A name added to `discriminants` also fires on objects outside closed unions (DOM events, external payloads): the list is a choice of the codebase. - -**Why**: `Match.tagsExhaustive`, `Match.discriminatorsExhaustive` and `$match` fail to compile when a variant is added; a comparison or a `switch` does not. - -**Options**: - -- `discriminants`: shared setting, see [Shared settings](#shared-settings). - -**Fix**: none - -### `no-manual-discriminant-construction` - -[↑ rules index](#rules-index) - -**Intent**: a union's variant is built by its constructor, never as an object literal with the discriminant. - -```ts -// no -const error = { _tag: "NotFound", id } - -// yes -const error = new NotFound({ id }) - -// no, with `discriminants: ["_tag", "eventType"]` -const event = { eventType: "PaymentStarted", id, payment } - -// yes -const event = PaymentStartedEvent.make({ id, payment }) -``` - -**Trigger**: an object literal with a discriminant property (also `"type"` or `["type"]`) whose value is a string literal. The discriminants are the names in `discriminants`. - -**Exemptions and blind spots**: values that are not literals (`"Ready" as const` included). Literals that are patterns or raw input, also nested: the arguments of `Match.when`, `Match.not`, of `.with(…)` on a ts-pattern `match(…)` chain, the expected value of an `expect(…)` matcher or `expect.*` helper, the input of `Schema.decode*(X)(…)`/`Schema.encode*(X)(…)`, the argument of `JSON.stringify`, and an argument whose parameter is annotated `unknown` in a function declared in the same file (a fake API's raw body). Transport payloads written as literals fire, as does raw data passed to an imported function or through a variable, and a name added to `discriminants` fires on objects outside closed unions: the list is a choice of the codebase. See `schema-struct-with-tag` (effecttsgo) for `Schema.Struct` with a `_tag` field. - -**Why**: a literal skips the constructor, so it carries none of the class's prototype, equality or validation, and drifts silently when the type changes. - -**Options**: - -- `discriminants`: shared setting, see [Shared settings](#shared-settings). - -**Fix**: none - -## Services and Layers - -### `service-port-shape-only` - -[↑ rules index](#rules-index) - -**Intent**: a port is a shape-only `Context.Service` (v3: `Context.Tag`), with no implementation attached. - -```ts -// no -class Agent extends Context.Service()("app/Agent", { make: makeAgent }) {} - -// yes -export class Agent extends Context.Service< - Agent, - { readonly search: (name: string) => Effect.Effect } ->()("app/agent/Agent") {} -``` - -**Trigger**: the second argument of `Context.Service<…>()(id, opts)`; a `static layer`, `static Default` or `static Live` member on a `Context.Service` or v3 `Context.Tag(id)<…>()` class; any `Effect.Service`. - -**Exemptions and blind spots**: a `Context.Service` or v3 `Context.GenericTag` assigned to a variable is not seen: see `service-not-as-class` (effecttsgo). Statics with other names slip through. - -**Why**: `make` and a static layer tie the port to a default implementation, while the port must stay a contract any adapter can satisfy. It is a convention, not Effect's idiom: Effect's own docs put `static readonly layer` on the service. - -**Options**: none - -**Fix**: none - -### `service-key-matches-name` - -[↑ rules index](#rules-index) - -**Intent**: a service's key is its class name, alone or after a path prefix. - -```ts -// no -export class GeocodingApis extends Context.Service()("GeocodingAPIs") {} - -// yes -export class GeocodingApis extends Context.Service()("GeocodingApis") {} - -// yes -export class GeocodingApis extends Context.Service()( - "app/geo/GeocodingApis", -) {} -``` - -**Trigger**: `class X extends Context.Service<…>()("key")`, or the v3 `Context.Tag("key")<…>()` and `Effect.Service()("key", …)`, with a literal key that is neither `"X"` nor ends with `"/X"`. - -**Exemptions and blind spots**: keys that are not literals (variables, templates with expressions). A `Context.Service` assigned to a variable is not seen: see `service-not-as-class` (effecttsgo). `deterministic-keys` (effecttsgo) with the `default` or `package-identifier` formula produces keys this rule accepts; with `default-hashed` the two contradict each other: enable only one. - -**Why**: the key is the service's identity in errors, traces and `Context` lookups; a key that drifts from the name, as after a rename, makes it hard to find the class behind a message. - -**Options**: none - -**Fix**: suggestion that replaces the last segment of the key with the class name - -### `service-built-with-of` - -[↑ rules index](#rules-index) - -**Intent**: the service a Layer provides is built with `Tag.of({…})`, not a bare object literal. - -```ts -// no -export const RepoLive = Layer.effect( - Repo, - Effect.gen(function* () { - const db = yield* Database - return { find: (id: RepoId) => db.get(id) } - }), -) - -// yes -export const RepoLive = Layer.effect( - Repo, - Effect.gen(function* () { - const db = yield* Database - return Repo.of({ find: (id: RepoId) => db.get(id) }) - }), -) -``` - -**Trigger**: an object literal passed as the value of `Layer.succeed(T, {…})`, returned by the function of `Layer.sync(T, () => ({…}))`, or returned by a top-level `return {…}` of the generator of `Layer.effect(T, Effect.gen(…))` or `Layer.scoped`; the curried `Layer.succeed(T)(…)` forms too. - -**Exemptions and blind spots**: a named factory (`Layer.sync(Repo, makeRepo)`) and a variable (`Layer.succeed(Repo, repo)`) are not inspected; `return` inside an `if` or a nested block, `Effect.gen(…).pipe(Layer.effect(T))` and generators other than `Effect.gen` slip through. - -**Why**: `T.of` names the service the object implements and keeps it checked against the shape if the literal moves out of the Layer; one form for every Layer. - -**Options**: none - -**Fix**: suggestion that wraps the literal in `T.of(…)` - -### `provide-named-layer` - -[↑ rules index](#rules-index) - -**Intent**: `Effect.provide` receives a named Layer, never an inline composition. - -```ts -// no -printMissing.pipe(Effect.provide(Layer.mergeAll(FileRaceList.layer, GoogleSheet.readerLayer))) - -// yes: the Layer is named in the entry point, provided in the dispatch -const missingLayer = Layer.mergeAll(FileRaceList.layer, GoogleSheet.readerLayer) -Missing: () => printMissing.pipe(Effect.provide(missingLayer)), -``` - -**Trigger**: an `Effect.provide` argument composed inline: `Layer.*(…)`, a ternary, an `&&`/`||`, a `match`/`$match`. - -**Exemptions and blind spots**: test files, where different fakes per test are idiomatic. Where `provide` sits (outside the entry point) needs types: see `strict-effect-provide` (effecttsgo). - -**Why**: an inline Layer cannot be reused and hides which adapters a branch chooses. When branches need different Layers, there is one `provide` per branch, all in the dispatch: a single Layer with every service would build adapters the command does not use. - -**Options**: - -- `testFiles`: shared setting, see [Shared settings](#shared-settings). - -**Fix**: none - -### `no-provide-on-definition` - -[↑ rules index](#rules-index) - -**Intent**: a program does not provide its own Layers; its caller does. - -```ts -// no -const printMissing = Effect.gen(function* () { … }).pipe(Effect.provide(missingLayer)) - -// yes: the program stays unprovided, its caller provides -const printMissing = Effect.gen(function* () { … }) -Missing: () => printMissing.pipe(Effect.provide(missingLayer)), -``` - -**Trigger**: `Effect.provide` applied to `Effect.gen(…)` or to `Effect.fn(…)(…)`, in all three forms: with `.pipe`, as an `Effect.fn` pipeable, data-first. - -**Exemptions and blind spots**: test files. A program passed directly to `Effect.run*`, also through `.pipe(…)` or data-first `Effect.*` combinators (`Effect.runPromise(Effect.gen(…).pipe(Effect.provide(layer), Effect.result))`): it is already being dispatched; through any other function it is still reported. A context captured in an enclosing generator with `const ctx = yield* Effect.context()` (also followed by `.pipe(…)`) and handed back to a method of the Layer being built: the caller chose the adapters when it built the Layer. A context obtained through a helper (`yield* contextWithoutSpan()`) is still reported. `provide` on a named program is allowed; `strict-effect-provide` (effecttsgo) reports it too. - -**Why**: a program that provides its own Layers can no longer be wired to different adapters by its caller. - -**Options**: - -- `testFiles`: shared setting, see [Shared settings](#shared-settings). - -**Fix**: none - -### `anti-slop-no-service-constructor-imports` - -[↑ rules index](#rules-index) - -**Intent**: runtime code obtains a service from its Layer, never by calling its `make…` constructor. - -```ts -// no: in src/runtime.ts -import { makeIssueService } from "./issue-service.ts" - -// yes -import { IssueService } from "./issue-service.ts" - -Effect.gen(function* () { - const issues = yield* IssueService -}) -``` - -**Trigger**: a named import of `make` followed by an uppercase letter (`makeIssueService`, also when renamed) from a relative module. - -**Exemptions and blind spots**: test files, which build services from their constructors to inject fakes. Non-relative imports (packages, path aliases), namespace and default imports, and constructors with another prefix slip through. The same import can also fire [`adapter-import-boundary`](#adapter-import-boundary). - -**Why**: calling the constructor wires its dependencies by hand, and its requirements stop propagating to the composition root. - -**Options**: - -- `testFiles`: shared setting, see [Shared settings](#shared-settings). - -**Fix**: none - -## Runtime and entry point - -### `run-only-in-runner` - -[↑ rules index](#rules-index) - -**Intent**: Effects run only in the program's runner, the entry point. - -```ts -// no -export const check = () => Effect.runPromise(pingDb(url)) - -// yes: in main.ts -NodeRuntime.runMain( - run(process.argv.slice(2)).pipe(Effect.provide(NodeServices.layer)) satisfies Effect.Effect< - void, - never - >, -) -``` - -**Trigger**: every reference, not just calls, to `Effect.run*`, `NodeRuntime.runMain`, `BunRuntime.runMain` and `ManagedRuntime.make` outside entry files. - -**Exemptions and blind spots**: test files, checked by [`prefer-effect-vitest`](#prefer-effect-vitest) instead. - -**Why**: logger, Layers and defect handling are configured in one place. - -**Options**: - -- `entryFiles`: shared setting, see [Shared settings](#shared-settings). -- `testFiles`: shared setting, see [Shared settings](#shared-settings). - -**Fix**: none - -### `prefer-effect-vitest` - -[↑ rules index](#rules-index) - -**Intent**: tests hand their Effects to `@effect/vitest` instead of running them. - -```ts -// no -test("…", async () => { - await Effect.runPromise(authorize({ role: "Manager" })) -}) - -// yes: fakes as Layers -import { effect } from "@effect/vitest" - -effect("…", () => authorize({ role: "Manager" }).pipe(Effect.provide(sheetWith(row)))) -``` - -**Trigger**: the same references as [`run-only-in-runner`](#run-only-in-runner), inside test files only. - -**Exemptions and blind spots**: projects where `@effect/vitest` cannot be found in a `node_modules` from the test file up, since the remedy is out of reach there; scattered runs in their tests go unreported. Every file outside `testFiles`, test helpers such as `src/testing/` included. - -**Why**: the test runtime brings `TestClock` and a scope per test, and fixtures provided as Layers replace services where the code reads them. - -**Options**: - -- `testFiles`: shared setting, see [Shared settings](#shared-settings). - -**Fix**: none - -### `all-errors-handled-at-boundary` - -[↑ rules index](#rules-index) - -**Intent**: the entry point runs an Effect whose error channel is closed to `never`. - -```ts -// no -export const POST = (request: Request) => Effect.runPromise(createEvent(request)) - -// yes: in an entry file -export const POST = (request: Request) => - Effect.runPromise(createEvent(request) satisfies Effect.Effect) - -// yes: a typed helper -const runBoundary = (effect: Effect.Effect) => Effect.runPromise(effect) -``` - -**Trigger**: `Effect.runPromise`, `runSync`, `runFork` and `runCallback` whose argument is not `… satisfies Effect.Effect`, a parameter declared with that type, or a program ending in `Effect.result`/`Effect.exit`, or the v3 `Effect.either` (`Effect.result(program)`, `program.pipe(…, Effect.result)`). - -**Exemptions and blind spots**: the `*Exit` variants, which return failures as values; `NodeRuntime.runMain`/`BunRuntime.runMain`, which log the Cause and exit with code 1, the right outcome for a process that cannot start; runners inside an `async` function that renders JSX itself, a Server Component, which hands failures to React rather than to an HTTP response; test files, where a rejected run fails the test with the error. The rule checks the shape; `tsc` gives the guarantee. - -**Why**: `Effect.runPromise` turns any error left over into a rejected promise, a generic 500. With `never`, a new untranslated error does not compile, and `R = never` forces all Layers to be provided. - -**Options**: - -- `testFiles`: shared setting, see [Shared settings](#shared-settings). - -**Fix**: none - -## Design and boundaries - -### `adapter-import-boundary` - -[↑ rules index](#rules-index) - -**Intent**: domain code and other adapters do not import an adapter; only entry files choose it. - -```ts -// no: in src/orders/place-order.ts -import { GoogleCalendar } from "../calendar/google/GoogleCalendar.ts" - -// yes: depend on the port, main.ts provides GoogleCalendar.layer -import { Calendar } from "../calendar/Calendar.ts" -``` - -**Trigger**: a relative import of a file in another directory that is an adapter: one of its `.ts` files (tests excluded) builds a `Layer` with `Layer.effect`, `succeed`, `sync`, `scoped`, `effectContext`, `unwrap`, `mock` and similar, or declares a v3 `Effect.Service`, which always carries its implementation. Composition alone (`mergeAll`, `provide`, `merge`) does not make an adapter. - -**Exemptions and blind spots**: entry files, where adapters are chosen, and test files, which compose the Layers they exercise. Non-relative imports (path aliases such as `@/calendar/google`) and directory imports through an `index.ts` (`"../google"`) slip through. On a layout other than one directory per adapter, check what it reports before trusting it. Infrastructure requirements in the port's `R` channel need types: see `leaking-requirements` (effecttsgo). - -**Why**: the adapter can be replaced without touching its consumers. - -**Options**: - -- `entryFiles`: shared setting, see [Shared settings](#shared-settings). -- `testFiles`: shared setting, see [Shared settings](#shared-settings). - -**Fix**: none - -### `no-transport-types-in-generator` - -[↑ rules index](#rules-index) - -**Intent**: the generator returns a domain value; conversion to a transport type happens in the second argument of `Effect.fn`. - -```ts -// no: an error branch inside the happy path -function* (request: Request) { - const credential = yield* sessionCredential - if (credential === undefined) return Response.redirect(new URL("/login", origin), 303) - // … -} - -// yes -const createEvent = Effect.fn("events.create")( - function* (request: Request) { - const credential = yield* sessionCredential // fails with Unauthenticated - const submission = yield* form(request) - return yield* apiCreateEvent(credential, submission) - }, - (effect, request) => - effect.pipe( - Effect.map((created) => Response.redirect(eventUrl(request, created), 303)), - Effect.catchTags({ Unauthenticated: () => Effect.succeed(toLogin(request)) }), - ), -) -``` - -**Trigger**: `new T(…)`, `T.method(…)` and `T(…)` inside an Effect generator, callbacks passed to `Effect.*` combinators included, when `T` is a transport type. - -**Exemptions and blind spots**: pipeables of `Effect.fn`, where the conversion must live. Functions the generator only defines, such as an HTTP handler it registers. `return yield* new Unauthenticated(…)` is a declared failure. An early `return` of a domain value that actually signals an error is indistinguishable from a success. - -**Why**: an early `return new Response(…)` on the happy path is an error branch disguised as success, and escapes exhaustive translation. - -**Options**: - -- `transportTypes`: default `["Response", "NextResponse"]`, replaced by the configured list. Add your own transport DTOs. - -**Fix**: none - -## Effectful functions - -### `prefer-effect-fn` - -[↑ rules index](#rules-index) - -**Intent**: an effectful function is `Effect.fn("name")`, and a named effect value has a span. - -```ts -// no -const outcomeFor = (name: string) => Effect.gen(function* () { … }).pipe(Effect.catch(toFailed)) -const refresh = Effect.gen(function* () { … }) - -// yes: extra combinators as arguments, not .pipe -const outcomeFor = Effect.fn("outcomeFor")(function* (name: string) { … }, Effect.catch(toFailed)) -const refresh = Effect.gen(function* () { … }).pipe(Effect.withSpan("refresh")) -``` - -**Trigger**: - -- a declared function, a variable or an object member that only returns `Effect.gen(…)`, even with `.pipe`; -- a variable or an object member whose value is `Effect.gen(…)` without `Effect.withSpan` in its `.pipe`; -- `Effect.fn(body)` without a name; -- `.pipe` on `Effect.fn(…)(…)`. - -**Exemptions and blind spots**: `Effect.gen` inline as an argument (`Layer.effect(Tag, Effect.gen(…))`, `Stream.unwrap`, callbacks, `it.effect`). Recursive functions: see [`untraced-recursion`](#untraced-recursion). - -**Why**: named stack traces and spans without wrapper functions. Combinators passed as arguments run inside the function's span and receive its arguments: `(effect, name) => effect.pipe(…)`. - -**Options**: none - -**Fix**: none - -### `untraced-recursion` - -[↑ rules index](#rules-index) - -**Intent**: a recursive effectful function uses `Effect.fnUntraced`; the entry point that starts the recursion is traced. - -```ts -// no -const walk = Effect.fn("walk")(function* (node: Node) { - for (const child of node.children) yield* walk(child) -}) - -// yes -const walk = Effect.fnUntraced(function* (node: Node) { - for (const child of node.children) yield* walk(child) -}) -export const scan = Effect.fn("scan")(function* (root: Node) { - return yield* walk(root) -}) -``` - -**Trigger**: an `Effect.fn` assigned to a variable that its own body calls again, even by passing it as a callback. - -**Exemptions and blind spots**: mutual recursion, recursion in pipeables. - -**Why**: with `Effect.fn` every level opens a span nested in the previous one. - -**Options**: none - -**Fix**: none - -### `single-style-per-function` - -[↑ rules index](#rules-index) - -**Intent**: a function is entirely Effect or not Effect at all. - -```ts -// no -export const POST = async (request: Request) => { - const form = await request.formData() - const created = await Effect.runPromise(Effect.result(createEvent(form))) - // … -} - -// yes: promises lifted with Effect.tryPromise -const createEvent = Effect.fn("events.create")(function* (request: Request) { - const form = yield* Effect.tryPromise({ - try: () => request.formData(), - catch: () => new BadRequest({ message: "invalid form data" }), - }) - // … -}) -``` - -**Trigger**: `async`, `await` and `.then(` in a function that builds Effects: an Effect generator, or a function using an `Effect.*` member. A `test`/`it` callback (`.only`, `.each(…)` and the like included) or a `beforeAll`/`afterAll`/`beforeEach`/`afterEach` hook, and in test files any other function except an Effect generator, is reported once, on the function, when more than one of its `await`s, or any `.then(`, involves Effect: has an `Effect.*` member in its expression, nested callbacks and `Effect.run*` included. - -**Exemptions and blind spots**: `Effect.run*` alone does not make a function effectful: it is how an async boundary hands over to Effect, and where it may appear is decided by [`run-only-in-runner`](#run-only-in-runner). An `async` function that renders JSX itself, not only in nested callbacks, is a Server Component: how it turns failures into UI is left to the application. A test, hook or test helper may await promise-based fixtures (a container, an identity provider), then one Effect program, and assert on its result. A step that reaches Effect only through a helper (`await run(seed)`) is not counted. - -**Why**: errors travel on two channels, exceptions and Effect, and neither sees them all. - -**Options**: - -- `testFiles`: shared setting, see [Shared settings](#shared-settings). - -**Fix**: none - -## Code shape - -### `no-nested-match` - -[↑ rules index](#rules-index) - -**Intent**: a match handler contains neither another match nor a ternary. - -```ts -// no -const run = (argv: ReadonlyArray) => - Result.match(parseArgs(argv), { - onFailure: usageError, - onSuccess: (command) => - Option.match(command.only, { onNone: () => fillAll, onSome: fillOnly }), - }) - -// yes, outside a generator: a named handler -const fill = (command: CliCommand) => - Option.match(command.only, { onNone: () => fillAll, onSome: fillOnly }) - -const run = (argv: ReadonlyArray) => - Result.match(parseArgs(argv), { onFailure: usageError, onSuccess: fill }) - -// yes, inside a generator: guard clauses -const run = Effect.fn("run")(function* (argv: ReadonlyArray) { - const parsed = parseArgs(argv) - if (Result.isFailure(parsed)) return yield* usageError(parsed.failure) - - const { only } = parsed.success - if (Option.isNone(only)) return yield* fillAll - - return yield* fillOnly(only.value) -}) -``` - -**Trigger**: a handler of `Option.match`, `Result.match`, `Exit.match`, `Either.match`, `$match` or `Match.valueTags` that is itself a data-last match (also `Match.type().pipe(…)` and `pipe(Match.type(), …)`), or that returns a match, a `Match.value(…).pipe(…)` or `pipe(Match.value(…), …)` chain or a ternary. - -**Exemptions and blind spots**: `if` inside handlers, and whatever they return from inside an `if` or another nested block; the handlers of an outer `Match.value`/`Match.type` chain; matches nested deeper than the returned value, or assigned to a variable before being returned. - -**Why**: two nested levels of choice hide which branch is the normal one. - -**Options**: none - -**Fix**: none - -### `no-yielded-match` - -[↑ rules index](#rules-index) - -**Intent**: inside an Effect generator, return early on the empty or failed case instead of yielding a match. - -```ts -// no -const save = Effect.fn("save")(function* (id: PolicyId) { - const found = yield* findPolicy(id) - return yield* Option.match(found, { - onNone: () => register(id), - onSome: (policy) => update(policy), - }) -}) - -// yes -const save = Effect.fn("save")(function* (id: PolicyId) { - const found = yield* findPolicy(id) - if (Option.isNone(found)) return yield* register(id) - - return yield* update(found.value) -}) -``` - -**Trigger**: `yield*` of `Option.match(x, {…})` or `Result.match(x, {…})` (v3: `Either.match`), or of a `x.pipe(…)`/`pipe(x, …)` ending in one of them, in the generator of `Effect.gen` or `Effect.fn`. - -**Exemptions and blind spots**: an `Option.match` with `onNone` → `Effect.fail(…)` and `onSome` → `Effect.succeed`: see `option-match-to-from-option` (effecttsgo). A handler that `no-nested-match` reports. Matches not yielded directly (assigned first, or inside `Effect.flatMap`) slip through. - -**Why**: the match splits the generator into two equal-weight branches; a guard clause leaves one main path of `yield*`. - -**Options**: none - -**Fix**: none - -### `no-inline-yield-star` - -[↑ rules index](#rules-index) - -**Intent**: a `yield*` result is bound to a `const` before being used. - -```ts -// no -function* () { - return yield* missingIn(yield* readSheet()) -} - -// yes -function* () { - const sheet = yield* readSheet() - return yield* missingIn(sheet) -} -``` - -**Trigger**: a `yield*` whose result is used inside a larger expression: argument, operand, member, property, template. - -**Exemptions and blind spots**: a `yield*` that is the whole value of a statement (`yield* x`, `return yield* x`, `if (yield* x)`, `for (… of yield* x)`), a declaration or an assignment. Also the whole branch of a ternary, or the right operand of `&&`/`||`/`??`, in one of those positions (`const a = cached ?? (yield* x)`): binding first would run the effect unconditionally. The autofix extracts every nested `yield*` into `const`s, innermost first, named after the argument's last identifier without a verb prefix (`readSheet()` → `sheet`). There is no autofix when moving the effect could change when or how often it runs: branches of a ternary or `&&`/`||`/`??` inside a larger expression, optional chaining, `while`/`for` conditions, statements without braces, another call evaluated before the `yield*`. - -**Why**: with several `yield*`s in one expression the order of effects can only be inferred from precedence. One `const` per effect makes the order the reading order and names the intermediate value. - -**Options**: none - -**Fix**: autofix - -### `no-effect-return-type` - -[↑ rules index](#rules-index) - -**Intent**: `Effect`, `Stream` and `Layer` return types are inferred, not annotated, except on exported declarations. - -```ts -// no -(effect, name): Effect.Effect => - -// yes -(effect, name) => - -// yes: an exported declaration keeps its annotation as a contract -export const findPrice = (id: PriceId): Effect.Effect => -``` - -**Trigger**: `Effect.Effect`, `Stream.Stream` or `Layer.Layer` in an annotated return type, even nested (`Option.Option>`, a function returning an `Effect`). - -**Exemptions and blind spots**: module-level declarations with `export` (`export const`, `export function`, `export default`), unless `checkExported` is on; methods of an exported object, functions an exported function returns, and `export { f }` lists are still checked. Recursion, and returns of different shapes that need unifying (`Effect.succeed` and `Effect.fail`), recognized from the shape of the `return`s. An `import type { Effect }` used as `Effect<…>` slips through. - -**Why**: the error and requirement channels collect what comes from everything the function calls; an error or a service added deep down would change every caller's annotation. An exported signature is the module's contract, like a named type: there the annotation makes such a change visible where it is published. To check a returned object against a named type, annotate the callback that builds it (`Effect.map(CurrentSession, (session): OrganizationContext => ({ … }))`) or use `satisfies`. - -**Options**: - -- `checkExported`: default `false`. Also checks exported declarations. - -**Fix**: suggestion that removes the annotation - -### `no-asymmetric-match-handlers` - -[↑ rules index](#rules-index) - -**Intent**: if one match handler delegates to a named function, the others do too. - -```ts -// no -Option.match(only, { - onNone: () => missingIn(sheet), - onSome: Effect.fn("onlyCandidate")(function* (name: string) { … }), -}) - -// yes -Option.match(only, { - onNone: () => missingIn(sheet), - onSome: (name) => onlyCandidate(sheet, name), -}) -``` - -**Trigger**: on the same matches as [`no-nested-match`](#no-nested-match), a handler with an inline body next to one that delegates. A handler delegates if it is a reference, a call, or a function returning only a call; it is inline if it has multiple statements, is a generator, or builds an `Effect.fn`/`Effect.gen`. - -**Exemptions and blind spots**: returned literals, templates, arrays and objects are values and count on neither side. - -**Why**: a branch saying _what_ next to one showing _how_ forces the reader to switch level halfway through the choice. - -**Options**: none - -**Fix**: none - -### `anti-slop-prefer-effect-match` - -[↑ rules index](#rules-index) - -**Intent**: a choice among several literal values of the same expression is a `Match`, not a chain of ternaries. - -```ts -// no -const label = kind === "a" ? "A" : kind === "b" ? "B" : "Other" - -// yes -const label = Match.value(kind).pipe( - Match.when("a", () => "A"), - Match.when("b", () => "B"), - Match.orElse(() => "Other"), -) -``` - -**Trigger**: a ternary chain of at least two levels where every condition compares the same expression, by source text, with a literal (`==`, `===`, `!=`, `!==`). - -**Exemptions and blind spots**: a single ternary, chains comparing different expressions, and the same expression written differently (`a.b` vs `a["b"]`). A chain returned by a match handler also fires [`no-nested-match`](#no-nested-match): extract the handler first, since a `Match.value` left inside it fires `no-nested-match` again. - -**Why**: a ternary chain hides which value is the fallback and cannot be made exhaustive. - -**Options**: none - -**Fix**: none - -## Schema - -### `exported-schema-identifier` - -[↑ rules index](#rules-index) - -**Intent**: an exported schema carries an `identifier` equal to its name. - -```ts -// no -export const EventBusEvents = Schema.Union([Created, Deleted]) - -// yes -export const EventBusEvents = Schema.Union([Created, Deleted]).annotate({ - identifier: "EventBusEvents", -}) -``` - -**Trigger**: `export const X = Schema.Struct(…)`, `Schema.Union(…)` or `Schema.Array(…)`, also followed by `.pipe(…)`, `.annotate(…)` or `.check(…)`, with no `identifier` in a `.annotate(…)` or `Schema.annotate(…)` of the chain (v3: `annotations`), or with a literal `identifier` other than `"X"`. - -**Exemptions and blind spots**: non-exported schemas (fragments reused through `.fields`), and `Schema.Class` and `Schema.TaggedError`, which carry the name already. A computed `identifier` is not compared. Other constructors (`Schema.TaggedStruct`, `Schema.Literals`, …), `export { X }` lists and chains through other methods slip through. An exported fragment reused only through `.fields` fires too, although the annotation does not reach the schemas that spread it: export the plain fields object instead (`export const BaseFields = { … }`). - -**Why**: without an `identifier`, decoding errors, JSON Schema and arbitraries describe the schema by its structure instead of its name. - -**Options**: none - -**Fix**: suggestion that corrects the `identifier`, or two that add it, `v3:` with `.annotations(…)` and `v4:` with `.annotate(…)` - -### `no-inline-schema-codec` - -[↑ rules index](#rules-index) - -**Intent**: a decoder or encoder is a named module-level constant, not built and applied inline. - -```ts -// no -const toPayment = (raw: unknown) => Schema.decodeUnknownSync(PaymentResponse)(raw) - -// yes -const decodePaymentResponse = Schema.decodeUnknownSync(PaymentResponse) - -const toPayment = (raw: unknown) => decodePaymentResponse(raw) -``` - -**Trigger**: an immediate application `Schema.decode*(X)(input)` or `Schema.encode*(X)(input)` (the `Effect`, `Exit`, `Option`, `Promise`, `Result` and `Sync` variants, `Unknown` included) inside a function, test callbacks included. - -**Exemptions and blind spots**: module scope, and the generator of `Layer.effect(T, Effect.gen(…))` or `Layer.effect(T)(Effect.gen(…))` (also `Layer.scoped`), which run once; functions nested in that generator, such as the service methods, are checked. Codecs built inside a function and applied later (`const decode = Schema.decodeUnknownEffect(X)`), codecs passed as callbacks (`Effect.flatMap(Schema.decodeUnknownEffect(X))`) and a Layer built through `.pipe(Layer.effect(T))` slip through. Whether the codec should be synchronous is not this rule's concern: see `schema-sync` (effecttsgo). - -**Why**: a named codec says what it decodes at the call site and is built once, instead of at every call. - -**Options**: none - -**Fix**: none - -## Config and secrets - -### `redacted-secret-names` - -[↑ rules index](#rules-index) - -**Intent**: a secret read from config or declared in a schema is `Redacted`. - -```ts -// no -serviceAccount: Config.schema(NonBlank, "GOOGLE_SERVICE_ACCOUNT_JSON") -const Session = Schema.Struct({ userId: UserId, accessToken: Schema.String }) - -// yes -serviceAccount: Config.schema(Schema.Redacted(NonBlank), "GOOGLE_SERVICE_ACCOUNT_JSON") -const Session = Schema.Struct({ userId: UserId, accessToken: Schema.Redacted(Schema.String) }) -``` - -**Trigger**: - -- a literal name read with `Config.*` that ends with `KEY`, `SECRET`, `TOKEN`, `PASSWORD`, `CREDENTIAL`, `CREDENTIALS` or `_JSON` (service account keys often travel as inline JSON), when it does not go through `Config.Redacted`, the v3 `Config.redacted` (also wrapping a config, `Config.redacted(Config.string(name))`), or `Config.schema(Schema.Redacted…(…), name)`; -- a field of `Schema.Struct({…})` or `Schema.Class("X")({…})` whose name is a `secretFields` entry or ends with it capitalized (`password` matches `dbPassword`), declared with a `Schema.*` constant such as `Schema.String`, also through `.pipe(…)`, `.check(…)`, `.annotate(…)`/`.annotations(…)` or `Schema.optional`/`optionalKey`/`optionalWith`/`NullOr`/`UndefinedOr`/`NullishOr`, with no `Schema.Redacted…` along the way. - -**Exemptions and blind spots**: a naming heuristic: secrets with other names slip through, non-secrets with these names must be suppressed. Fields declared with a named schema (`accessToken: AccessToken`) are not inspected; other constructors (`Schema.TaggedClass`, `Schema.TaggedStruct`, …) are not seen. `process.env` read outside `Config`: see `process-env` and `process-env-in-effect` (effecttsgo). - -**Why**: a `Redacted` value does not end up in logs or `toString`. - -**Options**: - -- `secretFields`: default `["password", "secret", "apiKey", "accessToken", "refreshToken", "idToken"]` (no generic `token`), replaced by the configured list. `Config` names are fixed. - -**Fix**: none diff --git a/docs/principles.md b/docs/principles.md index 90d7229..9ed9934 100644 --- a/docs/principles.md +++ b/docs/principles.md @@ -18,7 +18,7 @@ No rule uses type information. What can only be seen through types stays with ef ## No overlap with effecttsgo -A pattern already reported by `@effect/tsgo` does not become a rule. If effecttsgo covers it partially, the rule covers the rest, and its section in [`RULES.md`](../RULES.md) states where the boundary lies. +A pattern already reported by `@effect/tsgo` does not become a rule. If effecttsgo covers it partially, the rule covers the rest, and its file in the [rule catalog](user-guide/rules.md) states where the boundary lies. ## Effect 4 diff --git a/docs/rules-catalog-style.md b/docs/rules-catalog-style.md index 324208c..5d2e9dd 100644 --- a/docs/rules-catalog-style.md +++ b/docs/rules-catalog-style.md @@ -1,6 +1,6 @@ -# How to write `RULES.md` +# How to write the rule catalog -Writing rules for the rule catalog. They apply to every new or modified section. +Writing rules for the rule catalog: one file per rule, `docs/user-guide/rules/.md`, listed in the rules index, `docs/user-guide/rules.md`. They apply to every new or modified rule file. ## Reader @@ -14,17 +14,18 @@ Not the plugin maintainer: the rule's history, the sources it came from and impl ## Template ````md -### `rule-name` - -[↑ rules index](#rules-index) +--- +title: rule-name +group: Error channel +--- **Intent**: one sentence, in the imperative or as a prohibition. ```ts -// no +// ❌ no code the rule reports -// yes +// ✅ yes the compliant form ``` @@ -41,28 +42,32 @@ the compliant form **Fix**: none ```` -The heading and the back link below it are enforced by `rules-md.test.ts`. +The file name is the rule name; `rule-files.test.ts` checks that the catalog has exactly one file per rule of the plugin. `title` is the rule name and `group` the topic of its row in the rules index. The file has no heading: the website shows the title. + +The website parses this template in `website/src/site-content/`: it gives each rule file a page in the group of its frontmatter, in the order of the rules index, rewrites every relative `.md` link to the page it names, and fails the build naming the file when the rules index does not link it, when a link has no page, or when Intent, Trigger, Options or Fix is missing or out of shape (Options neither `none` nor a list, Fix not `none`, `autofix` or `suggestion…`, an example not opening with `// ❌ no` or without `// ✅ yes`). A change to the template must update that module and its tests. + +## Rules index -The website parses this template in `website/src/site-content/`: it groups rule pages by their `##` section, drops the back link, gives Rules index, Common limits and Shared settings a page each, rewrites every `#anchor` link to the page of its heading (a group's anchor to its first rule), and fails the build naming the link when an anchor has no page, or naming the rule when Intent, Trigger, Options or Fix is missing or out of shape (Options neither `none` nor a list, Fix not `none`, `autofix` or `suggestion…`, an example not opening with `// no` or without `// yes`). A change to the template must update that module and its tests. +`docs/user-guide/rules.md` has a `Topic | Rules` table: one row per group, its rules linked to their files in the order of the website sidebar. A new rule is added to the row of its group. Under Absorbed from anti-slop, the rules imported from `dmmulroy/anti-slop` and the anti-slop rules superseded by a dl-effect rule. -## Opening sections +## Shared settings page -- **Rules index**: a `Group | Rule` table in section order. The group appears only on its first row, linked to its section; every rule links to its own. -- **Shared settings**: one bullet per setting, with two sub-bullets: `used by`, listing the rules (a short note when a rule uses the setting differently from the others; rules that use it the same way share one bullet), and `default`, with the reason for any deliberate exclusion. +`docs/user-guide/shared-settings.md` is the only place that describes the settings. Under The settings, one bullet per setting, saying what it is for, with two sub-bullets: `used by`, listing the rules (a short note when a rule uses the setting differently from the others; rules that use it the same way share one bullet), and `default`, with the reason for any deliberate exclusion. A rule that gains or drops a setting updates its `used by`. ## Fields - **Intent**: one sentence that makes sense on its own. It states the norm, not the mechanism ("domain code does not import the implementation", not "reports relative imports of directories…"). -- **Example**: `no` first, then `yes`. The `no` is code that **this** rule reports: never an example of the pattern the rule does not detect. The minimum needed to recognize the case, at most about fifteen lines. Several `yes` only when they are genuinely different alternatives. +- **Example**: `// ❌ no` first, then `// ✅ yes`, each marker on its own comment line with its emoji. The `no` is code that **this** rule reports: never an example of the pattern the rule does not detect. The minimum needed to recognize the case, at most about fifteen lines. Several `yes` only when they are genuinely different alternatives. - **Trigger**: the reported syntactic forms, precise enough to predict whether a given piece of code fires. - **Exemptions and blind spots**: deliberate exemptions (entry, test, release) with their reason in half a sentence; then the cases that slip through (aliases, mutual recursion, requirements that need types). The reader must know that the rule's silence does not mean compliance. If another rule or diagnostic covers the gap, one line: "See `leaking-requirements` (effecttsgo)." Omit the field when there is nothing to say. - **Why**: the concrete cost of breaking the norm. One or two sentences. -- **Options**: a bold label like Intent, not a heading. One bullet per option: a shared setting reads "shared setting, see [Shared settings](../RULES.md#shared-settings).", one specific to the rule states its default. A rule without options has `**Options**: none` on one line. +- **Options**: a bold label like Intent, not a heading. One bullet per option: a shared setting reads "shared setting, see [Shared settings](../shared-settings.md).", one specific to the rule states its default. A rule without options has `**Options**: none` on one line. - **Fix**: `none`, `autofix` or `suggestion`; the conditions under which the fix does not apply go in Exemptions and blind spots. +- **Origin**: only on the rules absorbed from anti-slop, after Fix: "absorbed from [`dmmulroy/anti-slop`](https://github.com/dmmulroy/anti-slop), MIT-licensed: see [`LICENSE.anti-slop`](../../../LICENSE.anti-slop)." ## Redundancy and verbosity -- **Every fact in one place.** What applies to several rules (common limits, the `entryFiles`, `testFiles` and `discriminants` settings) lives in the opening sections and rules link to it. +- **Every fact in one place.** What applies to several rules (common limits, the `entryFiles`, `testFiles` and `discriminants` settings) lives in the guide pages [Common limits](user-guide/common-limits.md) and [Shared settings](user-guide/shared-settings.md), and rules link to them. - **Sibling rules** (same pattern): the second has Intent, Trigger, Exemptions, Options and Fix, and links to the first for the example and Why instead of repeating them. - **No source citations** (`AGENTS.md`, JSDoc, `ai-docs/`), no rule history, no numeric comparisons with effecttsgo: they do not belong in the catalog. - **No pattern guides.** How to structure tests without `@effect/vitest`, how to write a test runner: those are patterns, not rules, and do not belong in the catalog. diff --git a/docs/user-guide/README.md b/docs/user-guide/README.md new file mode 100644 index 0000000..d5940fc --- /dev/null +++ b/docs/user-guide/README.md @@ -0,0 +1,24 @@ +--- +title: "@doubleloop-io/oxlint-plugin-effect" +--- + +An oxlint plugin that enforces a catalog of patterns for Effect 4 code. + +The rules are written and tested against Effect 4. Where an Effect 3 API has the same intent, the rules recognize its v3 name too: each rule's Trigger names them. + +It complements the type-aware rules of [`@effect/tsgo`](alongside-effect-tsgo.md): it does not need them, and it checks what they do not. + +## Guide + +- [Installation](installation.md): the package and the Node and oxlint versions it requires. +- [Configuration](configuration.md): the `all` preset and picking rules. +- [Shared settings](shared-settings.md): the settings that describe your project, their defaults and the rules that use them. +- [Alongside `@effect/tsgo`](alongside-effect-tsgo.md): combining its presets with this one. +- [Default configuration](default-configuration.md): `all` with every setting and option spelled out. +- [Versioning](versioning.md): what a release may change and which oxlint versions are supported. +- [Troubleshooting](troubleshooting.md): the problems most often hit when adopting the plugin. + +## Rules + +- [Rules overview](rules.md): every rule, grouped by topic. +- [Common limits](common-limits.md): the limits every rule shares. diff --git a/docs/user-guide/alongside-effect-tsgo.md b/docs/user-guide/alongside-effect-tsgo.md new file mode 100644 index 0000000..2160e4f --- /dev/null +++ b/docs/user-guide/alongside-effect-tsgo.md @@ -0,0 +1,23 @@ +--- +title: Alongside `@effect/tsgo` +order: 4 +--- + +[`@effect/tsgo`](https://github.com/Effect-TS/tsgo) is the official Effect language service on top of the TypeScript Go compiler; its `effecttsgo` oxlint presets add more than 100 type-aware rules. This plugin does not need it, and its rules target what those presets do not check, so the two complement each other. To use both, follow its [Oxlint Setup guide](https://github.com/Effect-TS/tsgo/blob/main/docs/README.md) and put its preset in `extends` **before** `all`: + +```ts +import dlEffectAll from "@doubleloop-io/oxlint-plugin-effect/presets/all" +import { recommended as effectTsgoRecommended } from "@effect/tsgo/oxlint-presets" +import { defineConfig } from "oxlint" + +export default defineConfig({ extends: [effectTsgoRecommended, dlEffectAll] }) +``` + +```json +{ + "extends": [ + "./node_modules/@effect/tsgo/oxlint-presets/recommended.json", + "./node_modules/@doubleloop-io/oxlint-plugin-effect/dist/presets/all.json" + ] +} +``` diff --git a/docs/user-guide/common-limits.md b/docs/user-guide/common-limits.md new file mode 100644 index 0000000..d4a976b --- /dev/null +++ b/docs/user-guide/common-limits.md @@ -0,0 +1,10 @@ +--- +title: Common limits +order: 6 +--- + +The limits every rule shares. + +- **Syntax only**: no rule uses type information. Only two rules look past the file: [`adapter-import-boundary`](rules/adapter-import-boundary.md), to find which directories are adapters, and [`prefer-effect-vitest`](rules/prefer-effect-vitest.md), to find whether `@effect/vitest` is installed. +- **Literal names**: `Effect.gen` is recognized, `import { Effect as E }` or `import * as L from "effect/Layer"` slip through. On code that uses aliases, silence is not compliance. +- **Effect 4**: the rules are written against v4. Where a v3 API has the same intent, they recognize its v3 name too (`catchAll`, `Either`, `Context.Tag`, `Config.redacted`, …), and the Trigger names it. diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md new file mode 100644 index 0000000..c44a32a --- /dev/null +++ b/docs/user-guide/configuration.md @@ -0,0 +1,43 @@ +--- +title: Configuration +order: 2 +--- + +Extend the `all` preset. Prefer `oxlint.config.ts`, where `extends` takes config objects and the preset is imported by package name: + +```ts +import dlEffectAll from "@doubleloop-io/oxlint-plugin-effect/presets/all" +import { defineConfig } from "oxlint" + +export default defineConfig({ extends: [dlEffectAll] }) +``` + +With `.oxlintrc.json`, `extends` takes file paths only, so the preset is reached through `node_modules`: + +```json +{ + "extends": ["./node_modules/@doubleloop-io/oxlint-plugin-effect/dist/presets/all.json"] +} +``` + +`all` enables every rule at `warn`, so adopting it never breaks a build: look at the warnings first, then raise to `error` the rules you want to enforce. A `recommended` preset with reasoned severities will come from measurements on real codebases. + +To pick rules without the preset, load the plugin by package name and list the rules: + +```json +{ + "jsPlugins": ["@doubleloop-io/oxlint-plugin-effect"], + "rules": { + "dl-effect/no-effect-promise": "error", + "dl-effect/try-object-form": "error" + } +} +``` + +## Settings + +The settings that describe your project, such as its entry files and test files, are on [Shared settings](shared-settings.md). Their defaults fit a Node CLI: on another layout (Next.js, a monorepo), set them before reading the warnings. + +The other options and every default are in [Default configuration](default-configuration.md). + +To use it with the `@effect/tsgo` presets, see [Alongside `@effect/tsgo`](alongside-effect-tsgo.md). diff --git a/docs/user-guide/default-configuration.md b/docs/user-guide/default-configuration.md new file mode 100644 index 0000000..a8a4dd9 --- /dev/null +++ b/docs/user-guide/default-configuration.md @@ -0,0 +1,88 @@ +--- +title: Default configuration +order: 5 +--- + +`all` is equivalent to the config below, with every setting and option spelled out at its default. Both **replace** the defaults instead of extending them: see [Shared settings](shared-settings.md). + +```ts +import { defineConfig } from "oxlint" + +// Constructors that must not appear inside an Effect generator: the conversion to the +// transport belongs in the second argument of Effect.fn. Add your own transport DTOs. +const transportTypes = ["Response", "NextResponse"] + +// Schema fields holding a secret: a field matches an entry or ends with it capitalized +// (`password` matches `dbPassword`). No generic `token`: `nextPageToken` is not a secret. +const secretFields = ["password", "secret", "apiKey", "accessToken", "refreshToken", "idToken"] + +export default defineConfig({ + jsPlugins: ["@doubleloop-io/oxlint-plugin-effect"], + settings: { + "dl-effect": { + // Files allowed to run Effects (Effect.run*, runMain, ManagedRuntime.make) and to + // import adapters. `index.ts` is left out on purpose: as a barrel it would let + // adapters leak through re-exports. + entryFiles: ["**/main.ts", "**/cli.ts", "**/bin/**"], + // Files exempt from the rules that tests legitimately break. Helper directories such + // as `src/testing/` are support code, not tests, so they are not matched. + testFiles: [ + "**/*.test.*", + "**/*.spec.*", + "**/__tests__/**", + "**/test/**", + "**/tests/**", + ], + // Fields that discriminate a closed union, compared or switched on only through an + // exhaustive match and set only by a constructor. Add the ones your unions use, such + // as `type` or `kind`. + discriminants: ["_tag"], + }, + }, + // Every rule at `warn`, to measure noise without blocking. + rules: { + // Error channel + "dl-effect/no-throw-or-primitive-failure": "warn", + "dl-effect/try-object-form": "warn", + "dl-effect/no-effect-promise": "warn", + "dl-effect/no-parameterless-catch-all": "warn", + "dl-effect/split-success-path-from-error-handling": "warn", + "dl-effect/anti-slop-no-manual-effect-error-tag": "warn", + // Tagged values + "dl-effect/no-manual-discriminant-comparison": "warn", + "dl-effect/no-manual-discriminant-construction": "warn", + // Services & Layers + "dl-effect/service-port-shape-only": "warn", + "dl-effect/service-key-matches-name": "warn", + "dl-effect/service-built-with-of": "warn", + "dl-effect/provide-named-layer": "warn", + "dl-effect/no-provide-on-definition": "warn", + "dl-effect/anti-slop-no-service-constructor-imports": "warn", + // Runtime & entrypoint + "dl-effect/run-only-in-runner": "warn", + "dl-effect/prefer-effect-vitest": "warn", + "dl-effect/all-errors-handled-at-boundary": "warn", + // Design & boundaries + "dl-effect/adapter-import-boundary": "warn", + "dl-effect/no-transport-types-in-generator": ["warn", { transportTypes }], + // Effectful functions + "dl-effect/prefer-effect-fn": "warn", + "dl-effect/untraced-recursion": "warn", + "dl-effect/single-style-per-function": "warn", + // Code shape + "dl-effect/no-nested-match": "warn", + "dl-effect/no-yielded-match": "warn", + "dl-effect/no-inline-yield-star": "warn", + "dl-effect/no-effect-return-type": ["warn", { checkExported: false }], + "dl-effect/no-asymmetric-match-handlers": "warn", + "dl-effect/anti-slop-prefer-effect-match": "warn", + // Schema + "dl-effect/exported-schema-identifier": "warn", + "dl-effect/no-inline-schema-codec": "warn", + // Config & secrets + "dl-effect/redacted-secret-names": ["warn", { secretFields }], + }, +}) +``` + +To change a setting, declare it in `settings`; to change a rule option, extend `all` and override only that rule. diff --git a/docs/user-guide/installation.md b/docs/user-guide/installation.md new file mode 100644 index 0000000..308c39d --- /dev/null +++ b/docs/user-guide/installation.md @@ -0,0 +1,12 @@ +--- +title: Installation +order: 1 +--- + +```bash +pnpm add -D @doubleloop-io/oxlint-plugin-effect oxlint +``` + +Requires Node `^22.20.0 || >=24.8.0` and oxlint `^1.82.0`. What a release may change and which oxlint versions are supported: [Versioning](versioning.md). + +Then extend the `all` preset: see [Configuration](configuration.md). diff --git a/docs/user-guide/rules.md b/docs/user-guide/rules.md new file mode 100644 index 0000000..02c74b2 --- /dev/null +++ b/docs/user-guide/rules.md @@ -0,0 +1,26 @@ +--- +title: Rules overview +--- + +What each rule reports and why is on its page. Report false positives and missed cases in the [GitHub issues](https://github.com/doubleloop-io/oxlint-plugin-effect/issues). + +| Topic | Rules | +| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Error channel | [`no-throw-or-primitive-failure`](rules/no-throw-or-primitive-failure.md), [`try-object-form`](rules/try-object-form.md), [`no-effect-promise`](rules/no-effect-promise.md), [`no-parameterless-catch-all`](rules/no-parameterless-catch-all.md), [`split-success-path-from-error-handling`](rules/split-success-path-from-error-handling.md), [`anti-slop-no-manual-effect-error-tag`](rules/anti-slop-no-manual-effect-error-tag.md) | +| Tagged values | [`no-manual-discriminant-comparison`](rules/no-manual-discriminant-comparison.md), [`no-manual-discriminant-construction`](rules/no-manual-discriminant-construction.md) | +| Services and Layers | [`service-port-shape-only`](rules/service-port-shape-only.md), [`service-key-matches-name`](rules/service-key-matches-name.md), [`service-built-with-of`](rules/service-built-with-of.md), [`provide-named-layer`](rules/provide-named-layer.md), [`no-provide-on-definition`](rules/no-provide-on-definition.md), [`anti-slop-no-service-constructor-imports`](rules/anti-slop-no-service-constructor-imports.md) | +| Runtime and entry point | [`run-only-in-runner`](rules/run-only-in-runner.md), [`prefer-effect-vitest`](rules/prefer-effect-vitest.md), [`all-errors-handled-at-boundary`](rules/all-errors-handled-at-boundary.md) | +| Design and boundaries | [`adapter-import-boundary`](rules/adapter-import-boundary.md), [`no-transport-types-in-generator`](rules/no-transport-types-in-generator.md) | +| Effectful functions | [`prefer-effect-fn`](rules/prefer-effect-fn.md), [`untraced-recursion`](rules/untraced-recursion.md), [`single-style-per-function`](rules/single-style-per-function.md) | +| Code shape | [`no-nested-match`](rules/no-nested-match.md), [`no-yielded-match`](rules/no-yielded-match.md), [`no-inline-yield-star`](rules/no-inline-yield-star.md), [`no-effect-return-type`](rules/no-effect-return-type.md), [`no-asymmetric-match-handlers`](rules/no-asymmetric-match-handlers.md), [`anti-slop-prefer-effect-match`](rules/anti-slop-prefer-effect-match.md) | +| Schema | [`exported-schema-identifier`](rules/exported-schema-identifier.md), [`no-inline-schema-codec`](rules/no-inline-schema-codec.md) | +| Config and secrets | [`redacted-secret-names`](rules/redacted-secret-names.md) | + +## Absorbed from anti-slop + +Some rules come from the Effect rules of [`dmmulroy/anti-slop`](https://github.com/dmmulroy/anti-slop), MIT-licensed: see [`LICENSE.anti-slop`](../../LICENSE.anti-slop). + +| Status | Rules | +| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Imported | [`anti-slop-no-manual-effect-error-tag`](rules/anti-slop-no-manual-effect-error-tag.md), [`anti-slop-no-service-constructor-imports`](rules/anti-slop-no-service-constructor-imports.md), [`anti-slop-prefer-effect-match`](rules/anti-slop-prefer-effect-match.md) | +| Superseded | `no-manual-tag-comparison` → [`no-manual-discriminant-comparison`](rules/no-manual-discriminant-comparison.md), `no-manual-tagged-construction` → [`no-manual-discriminant-construction`](rules/no-manual-discriminant-construction.md) | diff --git a/docs/user-guide/rules/adapter-import-boundary.md b/docs/user-guide/rules/adapter-import-boundary.md new file mode 100644 index 0000000..eb8b6ff --- /dev/null +++ b/docs/user-guide/rules/adapter-import-boundary.md @@ -0,0 +1,27 @@ +--- +title: adapter-import-boundary +group: Design and boundaries +--- + +**Intent**: domain code and other adapters do not import an adapter; only entry files choose it. + +```ts +// ❌ no: in src/orders/place-order.ts +import { GoogleCalendar } from "../calendar/google/GoogleCalendar.ts" + +// ✅ yes: depend on the port, main.ts provides GoogleCalendar.layer +import { Calendar } from "../calendar/Calendar.ts" +``` + +**Trigger**: a relative import of a file in another directory that is an adapter: one of its `.ts` files (tests excluded) builds a `Layer` with `Layer.effect`, `succeed`, `sync`, `scoped`, `effectContext`, `unwrap`, `mock` and similar, or declares a v3 `Effect.Service`, which always carries its implementation. Composition alone (`mergeAll`, `provide`, `merge`) does not make an adapter. + +**Exemptions and blind spots**: entry files, where adapters are chosen, and test files, which compose the Layers they exercise. Non-relative imports (path aliases such as `@/calendar/google`) and directory imports through an `index.ts` (`"../google"`) slip through. On a layout other than one directory per adapter, check what it reports before trusting it. Infrastructure requirements in the port's `R` channel need types: see `leaking-requirements` (effecttsgo). + +**Why**: the adapter can be replaced without touching its consumers. + +**Options**: + +- `entryFiles`: shared setting, see [Shared settings](../shared-settings.md). +- `testFiles`: shared setting, see [Shared settings](../shared-settings.md). + +**Fix**: none diff --git a/docs/user-guide/rules/all-errors-handled-at-boundary.md b/docs/user-guide/rules/all-errors-handled-at-boundary.md new file mode 100644 index 0000000..4ad220a --- /dev/null +++ b/docs/user-guide/rules/all-errors-handled-at-boundary.md @@ -0,0 +1,30 @@ +--- +title: all-errors-handled-at-boundary +group: Runtime and entry point +--- + +**Intent**: the entry point runs an Effect whose error channel is closed to `never`. + +```ts +// ❌ no +export const POST = (request: Request) => Effect.runPromise(createEvent(request)) + +// ✅ yes: in an entry file +export const POST = (request: Request) => + Effect.runPromise(createEvent(request) satisfies Effect.Effect) + +// ✅ yes: a typed helper +const runBoundary = (effect: Effect.Effect) => Effect.runPromise(effect) +``` + +**Trigger**: `Effect.runPromise`, `runSync`, `runFork` and `runCallback` whose argument is not `… satisfies Effect.Effect`, a parameter declared with that type, or a program ending in `Effect.result`/`Effect.exit`, or the v3 `Effect.either` (`Effect.result(program)`, `program.pipe(…, Effect.result)`). + +**Exemptions and blind spots**: the `*Exit` variants, which return failures as values; `NodeRuntime.runMain`/`BunRuntime.runMain`, which log the Cause and exit with code 1, the right outcome for a process that cannot start; runners inside an `async` function that renders JSX itself, a Server Component, which hands failures to React rather than to an HTTP response; test files, where a rejected run fails the test with the error. The rule checks the shape; `tsc` gives the guarantee. + +**Why**: `Effect.runPromise` turns any error left over into a rejected promise, a generic 500. With `never`, a new untranslated error does not compile, and `R = never` forces all Layers to be provided. + +**Options**: + +- `testFiles`: shared setting, see [Shared settings](../shared-settings.md). + +**Fix**: none diff --git a/docs/user-guide/rules/anti-slop-no-manual-effect-error-tag.md b/docs/user-guide/rules/anti-slop-no-manual-effect-error-tag.md new file mode 100644 index 0000000..1459ce4 --- /dev/null +++ b/docs/user-guide/rules/anti-slop-no-manual-effect-error-tag.md @@ -0,0 +1,26 @@ +--- +title: anti-slop-no-manual-effect-error-tag +group: Error channel +--- + +**Intent**: a catch handler does not discriminate errors by `_tag`; `catchTag` and `catchReason` do. + +```ts +// ❌ no +program.pipe(Effect.catch((error) => (error._tag === "NotFound" ? recover : Effect.fail(error)))) + +// ✅ yes +program.pipe(Effect.catchTag("NotFound", () => recover)) +``` + +**Trigger**: an equality comparison between `_tag` (or `reason._tag`) and a string literal, or a `switch` on `_tag`, whose nearest enclosing function is a handler passed to `Effect.catch`, `catchAll` or `catchIf`. On `reason._tag` the message proposes `Effect.catchReason(s)`. + +**Exemptions and blind spots**: handlers of other combinators (`catchTag`, `catchCause`, `mapError`), and `_tag` checks in a function nested inside the handler. Outside these handlers the same checks belong to [`no-manual-discriminant-comparison`](no-manual-discriminant-comparison.md): the two never fire on the same node. + +**Why**: a hand-written dispatch keeps the caught errors in the type even when handled, and silently misses tags added later. + +**Options**: none + +**Fix**: none + +**Origin**: absorbed from [`dmmulroy/anti-slop`](https://github.com/dmmulroy/anti-slop), MIT-licensed: see [`LICENSE.anti-slop`](../../../LICENSE.anti-slop). diff --git a/docs/user-guide/rules/anti-slop-no-service-constructor-imports.md b/docs/user-guide/rules/anti-slop-no-service-constructor-imports.md new file mode 100644 index 0000000..bb48abc --- /dev/null +++ b/docs/user-guide/rules/anti-slop-no-service-constructor-imports.md @@ -0,0 +1,32 @@ +--- +title: anti-slop-no-service-constructor-imports +group: Services and Layers +--- + +**Intent**: runtime code obtains a service from its Layer, never by calling its `make…` constructor. + +```ts +// ❌ no: in src/runtime.ts +import { makeIssueService } from "./issue-service.ts" + +// ✅ yes +import { IssueService } from "./issue-service.ts" + +Effect.gen(function* () { + const issues = yield* IssueService +}) +``` + +**Trigger**: a named import of `make` followed by an uppercase letter (`makeIssueService`, also when renamed) from a relative module. + +**Exemptions and blind spots**: test files, which build services from their constructors to inject fakes. Non-relative imports (packages, path aliases), namespace and default imports, and constructors with another prefix slip through. The same import can also fire [`adapter-import-boundary`](adapter-import-boundary.md). + +**Why**: calling the constructor wires its dependencies by hand, and its requirements stop propagating to the composition root. + +**Options**: + +- `testFiles`: shared setting, see [Shared settings](../shared-settings.md). + +**Fix**: none + +**Origin**: absorbed from [`dmmulroy/anti-slop`](https://github.com/dmmulroy/anti-slop), MIT-licensed: see [`LICENSE.anti-slop`](../../../LICENSE.anti-slop). diff --git a/docs/user-guide/rules/anti-slop-prefer-effect-match.md b/docs/user-guide/rules/anti-slop-prefer-effect-match.md new file mode 100644 index 0000000..39d97d2 --- /dev/null +++ b/docs/user-guide/rules/anti-slop-prefer-effect-match.md @@ -0,0 +1,30 @@ +--- +title: anti-slop-prefer-effect-match +group: Code shape +--- + +**Intent**: a choice among several literal values of the same expression is a `Match`, not a chain of ternaries. + +```ts +// ❌ no +const label = kind === "a" ? "A" : kind === "b" ? "B" : "Other" + +// ✅ yes +const label = Match.value(kind).pipe( + Match.when("a", () => "A"), + Match.when("b", () => "B"), + Match.orElse(() => "Other"), +) +``` + +**Trigger**: a ternary chain of at least two levels where every condition compares the same expression, by source text, with a literal (`==`, `===`, `!=`, `!==`). + +**Exemptions and blind spots**: a single ternary, chains comparing different expressions, and the same expression written differently (`a.b` vs `a["b"]`). A chain returned by a match handler also fires [`no-nested-match`](no-nested-match.md): extract the handler first, since a `Match.value` left inside it fires `no-nested-match` again. + +**Why**: a ternary chain hides which value is the fallback and cannot be made exhaustive. + +**Options**: none + +**Fix**: none + +**Origin**: absorbed from [`dmmulroy/anti-slop`](https://github.com/dmmulroy/anti-slop), MIT-licensed: see [`LICENSE.anti-slop`](../../../LICENSE.anti-slop). diff --git a/docs/user-guide/rules/exported-schema-identifier.md b/docs/user-guide/rules/exported-schema-identifier.md new file mode 100644 index 0000000..f1c9399 --- /dev/null +++ b/docs/user-guide/rules/exported-schema-identifier.md @@ -0,0 +1,26 @@ +--- +title: exported-schema-identifier +group: Schema +--- + +**Intent**: an exported schema carries an `identifier` equal to its name. + +```ts +// ❌ no +export const EventBusEvents = Schema.Union([Created, Deleted]) + +// ✅ yes +export const EventBusEvents = Schema.Union([Created, Deleted]).annotate({ + identifier: "EventBusEvents", +}) +``` + +**Trigger**: `export const X = Schema.Struct(…)`, `Schema.Union(…)` or `Schema.Array(…)`, also followed by `.pipe(…)`, `.annotate(…)` or `.check(…)`, with no `identifier` in a `.annotate(…)` or `Schema.annotate(…)` of the chain (v3: `annotations`), or with a literal `identifier` other than `"X"`. + +**Exemptions and blind spots**: non-exported schemas (fragments reused through `.fields`), and `Schema.Class` and `Schema.TaggedError`, which carry the name already. A computed `identifier` is not compared. Other constructors (`Schema.TaggedStruct`, `Schema.Literals`, …), `export { X }` lists and chains through other methods slip through. An exported fragment reused only through `.fields` fires too, although the annotation does not reach the schemas that spread it: export the plain fields object instead (`export const BaseFields = { … }`). + +**Why**: without an `identifier`, decoding errors, JSON Schema and arbitraries describe the schema by its structure instead of its name. + +**Options**: none + +**Fix**: suggestion that corrects the `identifier`, or two that add it, `v3:` with `.annotations(…)` and `v4:` with `.annotate(…)` diff --git a/docs/user-guide/rules/no-asymmetric-match-handlers.md b/docs/user-guide/rules/no-asymmetric-match-handlers.md new file mode 100644 index 0000000..e9b0328 --- /dev/null +++ b/docs/user-guide/rules/no-asymmetric-match-handlers.md @@ -0,0 +1,30 @@ +--- +title: no-asymmetric-match-handlers +group: Code shape +--- + +**Intent**: if one match handler delegates to a named function, the others do too. + +```ts +// ❌ no +Option.match(only, { + onNone: () => missingIn(sheet), + onSome: Effect.fn("onlyCandidate")(function* (name: string) { … }), +}) + +// ✅ yes +Option.match(only, { + onNone: () => missingIn(sheet), + onSome: (name) => onlyCandidate(sheet, name), +}) +``` + +**Trigger**: on the same matches as [`no-nested-match`](no-nested-match.md), a handler with an inline body next to one that delegates. A handler delegates if it is a reference, a call, or a function returning only a call; it is inline if it has multiple statements, is a generator, or builds an `Effect.fn`/`Effect.gen`. + +**Exemptions and blind spots**: returned literals, templates, arrays and objects are values and count on neither side. + +**Why**: a branch saying _what_ next to one showing _how_ forces the reader to switch level halfway through the choice. + +**Options**: none + +**Fix**: none diff --git a/docs/user-guide/rules/no-effect-promise.md b/docs/user-guide/rules/no-effect-promise.md new file mode 100644 index 0000000..fd0b5f4 --- /dev/null +++ b/docs/user-guide/rules/no-effect-promise.md @@ -0,0 +1,26 @@ +--- +title: no-effect-promise +group: Error channel +--- + +**Intent**: a promise that can reject is lifted with [`Effect.tryPromise`](try-object-form.md), not `Effect.promise`. + +```ts +// ❌ no +Effect.promise(() => client.connect()) + +// ✅ yes +Effect.tryPromise({ try: () => client.connect(), catch: toConnectionError }) +``` + +**Trigger**: `Effect.promise` outside the release step of `acquireRelease`, `acquireUseRelease` and `addFinalizer`. + +**Exemptions and blind spots**: the release step, where a promise that cannot reject is the normal case. Test files, where a rejection during setup is a broken test and the defect fails it with the cause. Elsewhere, a promise that truly cannot reject must be suppressed by hand. + +**Why**: `Effect.promise` turns a rejection into a defect. + +**Options**: + +- `testFiles`: shared setting, see [Shared settings](../shared-settings.md). + +**Fix**: none diff --git a/docs/user-guide/rules/no-effect-return-type.md b/docs/user-guide/rules/no-effect-return-type.md new file mode 100644 index 0000000..0e02327 --- /dev/null +++ b/docs/user-guide/rules/no-effect-return-type.md @@ -0,0 +1,29 @@ +--- +title: no-effect-return-type +group: Code shape +--- + +**Intent**: `Effect`, `Stream` and `Layer` return types are inferred, not annotated, except on exported declarations. + +```ts +// ❌ no +(effect, name): Effect.Effect => + +// ✅ yes +(effect, name) => + +// ✅ yes: an exported declaration keeps its annotation as a contract +export const findPrice = (id: PriceId): Effect.Effect => +``` + +**Trigger**: `Effect.Effect`, `Stream.Stream` or `Layer.Layer` in an annotated return type, even nested (`Option.Option>`, a function returning an `Effect`). + +**Exemptions and blind spots**: module-level declarations with `export` (`export const`, `export function`, `export default`), unless `checkExported` is on; methods of an exported object, functions an exported function returns, and `export { f }` lists are still checked. Recursion, and returns of different shapes that need unifying (`Effect.succeed` and `Effect.fail`), recognized from the shape of the `return`s. An `import type { Effect }` used as `Effect<…>` slips through. + +**Why**: the error and requirement channels collect what comes from everything the function calls; an error or a service added deep down would change every caller's annotation. An exported signature is the module's contract, like a named type: there the annotation makes such a change visible where it is published. To check a returned object against a named type, annotate the callback that builds it (`Effect.map(CurrentSession, (session): OrganizationContext => ({ … }))`) or use `satisfies`. + +**Options**: + +- `checkExported`: default `false`. Also checks exported declarations. + +**Fix**: suggestion that removes the annotation diff --git a/docs/user-guide/rules/no-inline-schema-codec.md b/docs/user-guide/rules/no-inline-schema-codec.md new file mode 100644 index 0000000..a4f4b2b --- /dev/null +++ b/docs/user-guide/rules/no-inline-schema-codec.md @@ -0,0 +1,26 @@ +--- +title: no-inline-schema-codec +group: Schema +--- + +**Intent**: a decoder or encoder is a named module-level constant, not built and applied inline. + +```ts +// ❌ no +const toPayment = (raw: unknown) => Schema.decodeUnknownSync(PaymentResponse)(raw) + +// ✅ yes +const decodePaymentResponse = Schema.decodeUnknownSync(PaymentResponse) + +const toPayment = (raw: unknown) => decodePaymentResponse(raw) +``` + +**Trigger**: an immediate application `Schema.decode*(X)(input)` or `Schema.encode*(X)(input)` (the `Effect`, `Exit`, `Option`, `Promise`, `Result` and `Sync` variants, `Unknown` included) inside a function, test callbacks included. + +**Exemptions and blind spots**: module scope, and the generator of `Layer.effect(T, Effect.gen(…))` or `Layer.effect(T)(Effect.gen(…))` (also `Layer.scoped`), which run once; functions nested in that generator, such as the service methods, are checked. Codecs built inside a function and applied later (`const decode = Schema.decodeUnknownEffect(X)`), codecs passed as callbacks (`Effect.flatMap(Schema.decodeUnknownEffect(X))`) and a Layer built through `.pipe(Layer.effect(T))` slip through. Whether the codec should be synchronous is not this rule's concern: see `schema-sync` (effecttsgo). + +**Why**: a named codec says what it decodes at the call site and is built once, instead of at every call. + +**Options**: none + +**Fix**: none diff --git a/docs/user-guide/rules/no-inline-yield-star.md b/docs/user-guide/rules/no-inline-yield-star.md new file mode 100644 index 0000000..e984328 --- /dev/null +++ b/docs/user-guide/rules/no-inline-yield-star.md @@ -0,0 +1,29 @@ +--- +title: no-inline-yield-star +group: Code shape +--- + +**Intent**: a `yield*` result is bound to a `const` before being used. + +```ts +// ❌ no +function* () { + return yield* missingIn(yield* readSheet()) +} + +// ✅ yes +function* () { + const sheet = yield* readSheet() + return yield* missingIn(sheet) +} +``` + +**Trigger**: a `yield*` whose result is used inside a larger expression: argument, operand, member, property, template. + +**Exemptions and blind spots**: a `yield*` that is the whole value of a statement (`yield* x`, `return yield* x`, `if (yield* x)`, `for (… of yield* x)`), a declaration or an assignment. Also the whole branch of a ternary, or the right operand of `&&`/`||`/`??`, in one of those positions (`const a = cached ?? (yield* x)`): binding first would run the effect unconditionally. The autofix extracts every nested `yield*` into `const`s, innermost first, named after the argument's last identifier without a verb prefix (`readSheet()` → `sheet`). There is no autofix when moving the effect could change when or how often it runs: branches of a ternary or `&&`/`||`/`??` inside a larger expression, optional chaining, `while`/`for` conditions, statements without braces, another call evaluated before the `yield*`. + +**Why**: with several `yield*`s in one expression the order of effects can only be inferred from precedence. One `const` per effect makes the order the reading order and names the intermediate value. + +**Options**: none + +**Fix**: autofix diff --git a/docs/user-guide/rules/no-manual-discriminant-comparison.md b/docs/user-guide/rules/no-manual-discriminant-comparison.md new file mode 100644 index 0000000..bd7b53b --- /dev/null +++ b/docs/user-guide/rules/no-manual-discriminant-comparison.md @@ -0,0 +1,36 @@ +--- +title: no-manual-discriminant-comparison +group: Tagged values +--- + +**Intent**: branching on a union's discriminant goes through an exhaustive match, never through comparisons or `switch`. + +```ts +// ❌ no +switch (event._tag) { + case "Created": + return onCreated(event) + case "Deleted": + return onDeleted(event) +} + +// ✅ yes +Match.value(event).pipe(Match.tagsExhaustive({ Created: onCreated, Deleted: onDeleted })) + +// ✅ yes, with `discriminants: ["_tag", "type"]` +Match.value(payment).pipe( + Match.discriminatorsExhaustive("type")({ card: fromCard, transfer: fromTransfer }), +) +``` + +**Trigger**: an equality comparison between a discriminant (also `["type"]`) and a string literal, or a `switch` on a discriminant. The discriminants are the names in `discriminants`. + +**Exemptions and blind spots**: comparisons against a variable rather than a literal. On `_tag`, the handlers covered by [`anti-slop-no-manual-effect-error-tag`](anti-slop-no-manual-effect-error-tag.md): the two never fire on the same node. Guard clauses such as `if (x.type === "a") return …` fire too; on `_tag` use `Predicate.isTagged`. A `_tag` compared with a variant of Effect's own types (`Success`/`Failure` of `Result` and `Exit`, `Left`/`Right`, `Some`/`None`) is reported with their refinement as the remedy, such as `Result.isFailure`: those types cannot gain a variant; a `switch` is reported as usual. An exhaustive ts-pattern match is an equally valid remedy. A name added to `discriminants` also fires on objects outside closed unions (DOM events, external payloads): the list is a choice of the codebase. + +**Why**: `Match.tagsExhaustive`, `Match.discriminatorsExhaustive` and `$match` fail to compile when a variant is added; a comparison or a `switch` does not. + +**Options**: + +- `discriminants`: shared setting, see [Shared settings](../shared-settings.md). + +**Fix**: none diff --git a/docs/user-guide/rules/no-manual-discriminant-construction.md b/docs/user-guide/rules/no-manual-discriminant-construction.md new file mode 100644 index 0000000..0a29d8b --- /dev/null +++ b/docs/user-guide/rules/no-manual-discriminant-construction.md @@ -0,0 +1,32 @@ +--- +title: no-manual-discriminant-construction +group: Tagged values +--- + +**Intent**: a union's variant is built by its constructor, never as an object literal with the discriminant. + +```ts +// ❌ no +const error = { _tag: "NotFound", id } + +// ✅ yes +const error = new NotFound({ id }) + +// ❌ no, with `discriminants: ["_tag", "eventType"]` +const event = { eventType: "PaymentStarted", id, payment } + +// ✅ yes +const event = PaymentStartedEvent.make({ id, payment }) +``` + +**Trigger**: an object literal with a discriminant property (also `"type"` or `["type"]`) whose value is a string literal. The discriminants are the names in `discriminants`. + +**Exemptions and blind spots**: values that are not literals (`"Ready" as const` included). Literals that are patterns or raw input, also nested: the arguments of `Match.when`, `Match.not`, of `.with(…)` on a ts-pattern `match(…)` chain, the expected value of an `expect(…)` matcher or `expect.*` helper, the input of `Schema.decode*(X)(…)`/`Schema.encode*(X)(…)`, the argument of `JSON.stringify`, and an argument whose parameter is annotated `unknown` in a function declared in the same file (a fake API's raw body). Transport payloads written as literals fire, as does raw data passed to an imported function or through a variable, and a name added to `discriminants` fires on objects outside closed unions: the list is a choice of the codebase. See `schema-struct-with-tag` (effecttsgo) for `Schema.Struct` with a `_tag` field. + +**Why**: a literal skips the constructor, so it carries none of the class's prototype, equality or validation, and drifts silently when the type changes. + +**Options**: + +- `discriminants`: shared setting, see [Shared settings](../shared-settings.md). + +**Fix**: none diff --git a/docs/user-guide/rules/no-nested-match.md b/docs/user-guide/rules/no-nested-match.md new file mode 100644 index 0000000..b697ad0 --- /dev/null +++ b/docs/user-guide/rules/no-nested-match.md @@ -0,0 +1,44 @@ +--- +title: no-nested-match +group: Code shape +--- + +**Intent**: a match handler contains neither another match nor a ternary. + +```ts +// ❌ no +const run = (argv: ReadonlyArray) => + Result.match(parseArgs(argv), { + onFailure: usageError, + onSuccess: (command) => + Option.match(command.only, { onNone: () => fillAll, onSome: fillOnly }), + }) + +// ✅ yes, outside a generator: a named handler +const fill = (command: CliCommand) => + Option.match(command.only, { onNone: () => fillAll, onSome: fillOnly }) + +const run = (argv: ReadonlyArray) => + Result.match(parseArgs(argv), { onFailure: usageError, onSuccess: fill }) + +// ✅ yes, inside a generator: guard clauses +const run = Effect.fn("run")(function* (argv: ReadonlyArray) { + const parsed = parseArgs(argv) + if (Result.isFailure(parsed)) return yield* usageError(parsed.failure) + + const { only } = parsed.success + if (Option.isNone(only)) return yield* fillAll + + return yield* fillOnly(only.value) +}) +``` + +**Trigger**: a handler of `Option.match`, `Result.match`, `Exit.match`, `Either.match`, `$match` or `Match.valueTags` that is itself a data-last match (also `Match.type().pipe(…)` and `pipe(Match.type(), …)`), or that returns a match, a `Match.value(…).pipe(…)` or `pipe(Match.value(…), …)` chain or a ternary. + +**Exemptions and blind spots**: `if` inside handlers, and whatever they return from inside an `if` or another nested block; the handlers of an outer `Match.value`/`Match.type` chain; matches nested deeper than the returned value, or assigned to a variable before being returned. + +**Why**: two nested levels of choice hide which branch is the normal one. + +**Options**: none + +**Fix**: none diff --git a/docs/user-guide/rules/no-parameterless-catch-all.md b/docs/user-guide/rules/no-parameterless-catch-all.md new file mode 100644 index 0000000..acd74f8 --- /dev/null +++ b/docs/user-guide/rules/no-parameterless-catch-all.md @@ -0,0 +1,28 @@ +--- +title: no-parameterless-catch-all +group: Error channel +--- + +**Intent**: errors are caught by tag; a fallback that ignores the error is spelled `orElseSucceed`/`orElse`, never a catch-all with an ignored parameter. + +```ts +// ❌ no +Effect.catch(() => Effect.succeed(fallback)) + +// ✅ yes +Effect.catchTag("AgentTimeout", () => Effect.succeed(skip)) +Effect.catchTag(["ParseError", "ReservedPortError"], () => Effect.succeed(3000)) + +// ✅ yes: every failure truly means the same fallback +Effect.orElseSucceed(() => fallback) +``` + +**Trigger**: `Effect.catch`, `catchAll`, `catchCause` and `catchEager` with a parameterless handler. + +**Exemptions and blind spots**: a catch-all that discriminates on `_tag` by hand: see [`anti-slop-no-manual-effect-error-tag`](anti-slop-no-manual-effect-error-tag.md), and `catch-all-to-map-error`, `catch-all-tag-dispatch-to-catch-tag` and `catch-to-ignore` (effecttsgo). + +**Why**: a catch-all that ignores its parameter also swallows the errors added later, which `catchTag` would leave visible in the type. + +**Options**: none + +**Fix**: none diff --git a/docs/user-guide/rules/no-provide-on-definition.md b/docs/user-guide/rules/no-provide-on-definition.md new file mode 100644 index 0000000..dc5b57b --- /dev/null +++ b/docs/user-guide/rules/no-provide-on-definition.md @@ -0,0 +1,27 @@ +--- +title: no-provide-on-definition +group: Services and Layers +--- + +**Intent**: a program does not provide its own Layers; its caller does. + +```ts +// ❌ no +const printMissing = Effect.gen(function* () { … }).pipe(Effect.provide(missingLayer)) + +// ✅ yes: the program stays unprovided, its caller provides +const printMissing = Effect.gen(function* () { … }) +Missing: () => printMissing.pipe(Effect.provide(missingLayer)), +``` + +**Trigger**: `Effect.provide` applied to `Effect.gen(…)` or to `Effect.fn(…)(…)`, in all three forms: with `.pipe`, as an `Effect.fn` pipeable, data-first. + +**Exemptions and blind spots**: test files. A program passed directly to `Effect.run*`, also through `.pipe(…)` or data-first `Effect.*` combinators (`Effect.runPromise(Effect.gen(…).pipe(Effect.provide(layer), Effect.result))`): it is already being dispatched; through any other function it is still reported. A context captured in an enclosing generator with `const ctx = yield* Effect.context()` (also followed by `.pipe(…)`) and handed back to a method of the Layer being built: the caller chose the adapters when it built the Layer. A context obtained through a helper (`yield* contextWithoutSpan()`) is still reported. `provide` on a named program is allowed; `strict-effect-provide` (effecttsgo) reports it too. + +**Why**: a program that provides its own Layers can no longer be wired to different adapters by its caller. + +**Options**: + +- `testFiles`: shared setting, see [Shared settings](../shared-settings.md). + +**Fix**: none diff --git a/docs/user-guide/rules/no-throw-or-primitive-failure.md b/docs/user-guide/rules/no-throw-or-primitive-failure.md new file mode 100644 index 0000000..810b619 --- /dev/null +++ b/docs/user-guide/rules/no-throw-or-primitive-failure.md @@ -0,0 +1,34 @@ +--- +title: no-throw-or-primitive-failure +group: Error channel +--- + +**Intent**: an expected failure is a tagged error, never a thrown or primitive value. + +```ts +// ❌ no +Effect.gen(function* () { + if (tab === undefined) throw new Error("tab not found") +}) +Effect.fail("tab not found") + +// ✅ yes +export class SheetTabNotFoundError extends Schema.TaggedError()( + "SheetTabNotFoundError", + { spreadsheetId: Schema.String, message: Schema.String }, +) {} + +Effect.fail(new SheetTabNotFoundError({ spreadsheetId, message: "tab not found" })) +``` + +**Trigger**: a `throw` directly inside a generator passed to `Effect.gen`/`Effect.fn`; `Effect.fail` with a literal or a template. + +**Exemptions and blind spots**: `Effect.fail` with a literal in test files, where a synthetic failure feeds code generic over the error; a `throw` in a test generator is still reported. A `throw` inside a nested callback. `Effect.fail(new Error(…))` and `class X extends Error`: see `global-error-in-effect-failure` and `extends-native-error` (effecttsgo). + +**Why**: the typed error channel discriminates only on tags. A `throw` in the generator becomes a defect, outside the error channel. + +**Options**: + +- `testFiles`: shared setting, see [Shared settings](../shared-settings.md). + +**Fix**: none diff --git a/docs/user-guide/rules/no-transport-types-in-generator.md b/docs/user-guide/rules/no-transport-types-in-generator.md new file mode 100644 index 0000000..336c5a8 --- /dev/null +++ b/docs/user-guide/rules/no-transport-types-in-generator.md @@ -0,0 +1,41 @@ +--- +title: no-transport-types-in-generator +group: Design and boundaries +--- + +**Intent**: the generator returns a domain value; conversion to a transport type happens in the second argument of `Effect.fn`. + +```ts +// ❌ no: an error branch inside the happy path +function* (request: Request) { + const credential = yield* sessionCredential + if (credential === undefined) return Response.redirect(new URL("/login", origin), 303) + // … +} + +// ✅ yes +const createEvent = Effect.fn("events.create")( + function* (request: Request) { + const credential = yield* sessionCredential // fails with Unauthenticated + const submission = yield* form(request) + return yield* apiCreateEvent(credential, submission) + }, + (effect, request) => + effect.pipe( + Effect.map((created) => Response.redirect(eventUrl(request, created), 303)), + Effect.catchTags({ Unauthenticated: () => Effect.succeed(toLogin(request)) }), + ), +) +``` + +**Trigger**: `new T(…)`, `T.method(…)` and `T(…)` inside an Effect generator, callbacks passed to `Effect.*` combinators included, when `T` is a transport type. + +**Exemptions and blind spots**: pipeables of `Effect.fn`, where the conversion must live. Functions the generator only defines, such as an HTTP handler it registers. `return yield* new Unauthenticated(…)` is a declared failure. An early `return` of a domain value that actually signals an error is indistinguishable from a success. + +**Why**: an early `return new Response(…)` on the happy path is an error branch disguised as success, and escapes exhaustive translation. + +**Options**: + +- `transportTypes`: default `["Response", "NextResponse"]`, replaced by the configured list. Add your own transport DTOs. + +**Fix**: none diff --git a/docs/user-guide/rules/no-yielded-match.md b/docs/user-guide/rules/no-yielded-match.md new file mode 100644 index 0000000..3ced648 --- /dev/null +++ b/docs/user-guide/rules/no-yielded-match.md @@ -0,0 +1,35 @@ +--- +title: no-yielded-match +group: Code shape +--- + +**Intent**: inside an Effect generator, return early on the empty or failed case instead of yielding a match. + +```ts +// ❌ no +const save = Effect.fn("save")(function* (id: PolicyId) { + const found = yield* findPolicy(id) + return yield* Option.match(found, { + onNone: () => register(id), + onSome: (policy) => update(policy), + }) +}) + +// ✅ yes +const save = Effect.fn("save")(function* (id: PolicyId) { + const found = yield* findPolicy(id) + if (Option.isNone(found)) return yield* register(id) + + return yield* update(found.value) +}) +``` + +**Trigger**: `yield*` of `Option.match(x, {…})` or `Result.match(x, {…})` (v3: `Either.match`), or of a `x.pipe(…)`/`pipe(x, …)` ending in one of them, in the generator of `Effect.gen` or `Effect.fn`. + +**Exemptions and blind spots**: an `Option.match` with `onNone` → `Effect.fail(…)` and `onSome` → `Effect.succeed`: see `option-match-to-from-option` (effecttsgo). A handler that `no-nested-match` reports. Matches not yielded directly (assigned first, or inside `Effect.flatMap`) slip through. + +**Why**: the match splits the generator into two equal-weight branches; a guard clause leaves one main path of `yield*`. + +**Options**: none + +**Fix**: none diff --git a/docs/user-guide/rules/prefer-effect-fn.md b/docs/user-guide/rules/prefer-effect-fn.md new file mode 100644 index 0000000..fc99f1e --- /dev/null +++ b/docs/user-guide/rules/prefer-effect-fn.md @@ -0,0 +1,31 @@ +--- +title: prefer-effect-fn +group: Effectful functions +--- + +**Intent**: an effectful function is `Effect.fn("name")`, and a named effect value has a span. + +```ts +// ❌ no +const outcomeFor = (name: string) => Effect.gen(function* () { … }).pipe(Effect.catch(toFailed)) +const refresh = Effect.gen(function* () { … }) + +// ✅ yes: extra combinators as arguments, not .pipe +const outcomeFor = Effect.fn("outcomeFor")(function* (name: string) { … }, Effect.catch(toFailed)) +const refresh = Effect.gen(function* () { … }).pipe(Effect.withSpan("refresh")) +``` + +**Trigger**: + +- a declared function, a variable or an object member that only returns `Effect.gen(…)`, even with `.pipe`; +- a variable or an object member whose value is `Effect.gen(…)` without `Effect.withSpan` in its `.pipe`; +- `Effect.fn(body)` without a name; +- `.pipe` on `Effect.fn(…)(…)`. + +**Exemptions and blind spots**: `Effect.gen` inline as an argument (`Layer.effect(Tag, Effect.gen(…))`, `Stream.unwrap`, callbacks, `it.effect`). Recursive functions: see [`untraced-recursion`](untraced-recursion.md). + +**Why**: named stack traces and spans without wrapper functions. Combinators passed as arguments run inside the function's span and receive its arguments: `(effect, name) => effect.pipe(…)`. + +**Options**: none + +**Fix**: none diff --git a/docs/user-guide/rules/prefer-effect-vitest.md b/docs/user-guide/rules/prefer-effect-vitest.md new file mode 100644 index 0000000..f174a55 --- /dev/null +++ b/docs/user-guide/rules/prefer-effect-vitest.md @@ -0,0 +1,30 @@ +--- +title: prefer-effect-vitest +group: Runtime and entry point +--- + +**Intent**: tests hand their Effects to `@effect/vitest` instead of running them. + +```ts +// ❌ no +test("…", async () => { + await Effect.runPromise(authorize({ role: "Manager" })) +}) + +// ✅ yes: fakes as Layers +import { effect } from "@effect/vitest" + +effect("…", () => authorize({ role: "Manager" }).pipe(Effect.provide(sheetWith(row)))) +``` + +**Trigger**: the same references as [`run-only-in-runner`](run-only-in-runner.md), inside test files only. + +**Exemptions and blind spots**: projects where `@effect/vitest` cannot be found in a `node_modules` from the test file up, since the remedy is out of reach there; scattered runs in their tests go unreported. Every file outside `testFiles`, test helpers such as `src/testing/` included. + +**Why**: the test runtime brings `TestClock` and a scope per test, and fixtures provided as Layers replace services where the code reads them. + +**Options**: + +- `testFiles`: shared setting, see [Shared settings](../shared-settings.md). + +**Fix**: none diff --git a/docs/user-guide/rules/provide-named-layer.md b/docs/user-guide/rules/provide-named-layer.md new file mode 100644 index 0000000..5fbc23b --- /dev/null +++ b/docs/user-guide/rules/provide-named-layer.md @@ -0,0 +1,27 @@ +--- +title: provide-named-layer +group: Services and Layers +--- + +**Intent**: `Effect.provide` receives a named Layer, never an inline composition. + +```ts +// ❌ no +printMissing.pipe(Effect.provide(Layer.mergeAll(FileRaceList.layer, GoogleSheet.readerLayer))) + +// ✅ yes: the Layer is named in the entry point, provided in the dispatch +const missingLayer = Layer.mergeAll(FileRaceList.layer, GoogleSheet.readerLayer) +Missing: () => printMissing.pipe(Effect.provide(missingLayer)), +``` + +**Trigger**: an `Effect.provide` argument composed inline: `Layer.*(…)`, a ternary, an `&&`/`||`, a `match`/`$match`. + +**Exemptions and blind spots**: test files, where different fakes per test are idiomatic. Where `provide` sits (outside the entry point) needs types: see `strict-effect-provide` (effecttsgo). + +**Why**: an inline Layer cannot be reused and hides which adapters a branch chooses. When branches need different Layers, there is one `provide` per branch, all in the dispatch: a single Layer with every service would build adapters the command does not use. + +**Options**: + +- `testFiles`: shared setting, see [Shared settings](../shared-settings.md). + +**Fix**: none diff --git a/docs/user-guide/rules/redacted-secret-names.md b/docs/user-guide/rules/redacted-secret-names.md new file mode 100644 index 0000000..2c5df7d --- /dev/null +++ b/docs/user-guide/rules/redacted-secret-names.md @@ -0,0 +1,31 @@ +--- +title: redacted-secret-names +group: Config and secrets +--- + +**Intent**: a secret read from config or declared in a schema is `Redacted`. + +```ts +// ❌ no +serviceAccount: Config.schema(NonBlank, "GOOGLE_SERVICE_ACCOUNT_JSON") +const Session = Schema.Struct({ userId: UserId, accessToken: Schema.String }) + +// ✅ yes +serviceAccount: Config.schema(Schema.Redacted(NonBlank), "GOOGLE_SERVICE_ACCOUNT_JSON") +const Session = Schema.Struct({ userId: UserId, accessToken: Schema.Redacted(Schema.String) }) +``` + +**Trigger**: + +- a literal name read with `Config.*` that ends with `KEY`, `SECRET`, `TOKEN`, `PASSWORD`, `CREDENTIAL`, `CREDENTIALS` or `_JSON` (service account keys often travel as inline JSON), when it does not go through `Config.Redacted`, the v3 `Config.redacted` (also wrapping a config, `Config.redacted(Config.string(name))`), or `Config.schema(Schema.Redacted…(…), name)`; +- a field of `Schema.Struct({…})` or `Schema.Class("X")({…})` whose name is a `secretFields` entry or ends with it capitalized (`password` matches `dbPassword`), declared with a `Schema.*` constant such as `Schema.String`, also through `.pipe(…)`, `.check(…)`, `.annotate(…)`/`.annotations(…)` or `Schema.optional`/`optionalKey`/`optionalWith`/`NullOr`/`UndefinedOr`/`NullishOr`, with no `Schema.Redacted…` along the way. + +**Exemptions and blind spots**: a naming heuristic: secrets with other names slip through, non-secrets with these names must be suppressed. Fields declared with a named schema (`accessToken: AccessToken`) are not inspected; other constructors (`Schema.TaggedClass`, `Schema.TaggedStruct`, …) are not seen. `process.env` read outside `Config`: see `process-env` and `process-env-in-effect` (effecttsgo). + +**Why**: a `Redacted` value does not end up in logs or `toString`. + +**Options**: + +- `secretFields`: default `["password", "secret", "apiKey", "accessToken", "refreshToken", "idToken"]` (no generic `token`), replaced by the configured list. `Config` names are fixed. + +**Fix**: none diff --git a/docs/user-guide/rules/run-only-in-runner.md b/docs/user-guide/rules/run-only-in-runner.md new file mode 100644 index 0000000..0e61ed2 --- /dev/null +++ b/docs/user-guide/rules/run-only-in-runner.md @@ -0,0 +1,32 @@ +--- +title: run-only-in-runner +group: Runtime and entry point +--- + +**Intent**: Effects run only in the program's runner, the entry point. + +```ts +// ❌ no +export const check = () => Effect.runPromise(pingDb(url)) + +// ✅ yes: in main.ts +NodeRuntime.runMain( + run(process.argv.slice(2)).pipe(Effect.provide(NodeServices.layer)) satisfies Effect.Effect< + void, + never + >, +) +``` + +**Trigger**: every reference, not just calls, to `Effect.run*`, `NodeRuntime.runMain`, `BunRuntime.runMain` and `ManagedRuntime.make` outside entry files. + +**Exemptions and blind spots**: test files, checked by [`prefer-effect-vitest`](prefer-effect-vitest.md) instead. + +**Why**: logger, Layers and defect handling are configured in one place. + +**Options**: + +- `entryFiles`: shared setting, see [Shared settings](../shared-settings.md). +- `testFiles`: shared setting, see [Shared settings](../shared-settings.md). + +**Fix**: none diff --git a/docs/user-guide/rules/service-built-with-of.md b/docs/user-guide/rules/service-built-with-of.md new file mode 100644 index 0000000..adc10ac --- /dev/null +++ b/docs/user-guide/rules/service-built-with-of.md @@ -0,0 +1,36 @@ +--- +title: service-built-with-of +group: Services and Layers +--- + +**Intent**: the service a Layer provides is built with `Tag.of({…})`, not a bare object literal. + +```ts +// ❌ no +export const RepoLive = Layer.effect( + Repo, + Effect.gen(function* () { + const db = yield* Database + return { find: (id: RepoId) => db.get(id) } + }), +) + +// ✅ yes +export const RepoLive = Layer.effect( + Repo, + Effect.gen(function* () { + const db = yield* Database + return Repo.of({ find: (id: RepoId) => db.get(id) }) + }), +) +``` + +**Trigger**: an object literal passed as the value of `Layer.succeed(T, {…})`, returned by the function of `Layer.sync(T, () => ({…}))`, or returned by a top-level `return {…}` of the generator of `Layer.effect(T, Effect.gen(…))` or `Layer.scoped`; the curried `Layer.succeed(T)(…)` forms too. + +**Exemptions and blind spots**: a named factory (`Layer.sync(Repo, makeRepo)`) and a variable (`Layer.succeed(Repo, repo)`) are not inspected; `return` inside an `if` or a nested block, `Effect.gen(…).pipe(Layer.effect(T))` and generators other than `Effect.gen` slip through. + +**Why**: `T.of` names the service the object implements and keeps it checked against the shape if the literal moves out of the Layer; one form for every Layer. + +**Options**: none + +**Fix**: suggestion that wraps the literal in `T.of(…)` diff --git a/docs/user-guide/rules/service-key-matches-name.md b/docs/user-guide/rules/service-key-matches-name.md new file mode 100644 index 0000000..a62bdad --- /dev/null +++ b/docs/user-guide/rules/service-key-matches-name.md @@ -0,0 +1,29 @@ +--- +title: service-key-matches-name +group: Services and Layers +--- + +**Intent**: a service's key is its class name, alone or after a path prefix. + +```ts +// ❌ no +export class GeocodingApis extends Context.Service()("GeocodingAPIs") {} + +// ✅ yes +export class GeocodingApis extends Context.Service()("GeocodingApis") {} + +// ✅ yes +export class GeocodingApis extends Context.Service()( + "app/geo/GeocodingApis", +) {} +``` + +**Trigger**: `class X extends Context.Service<…>()("key")`, or the v3 `Context.Tag("key")<…>()` and `Effect.Service()("key", …)`, with a literal key that is neither `"X"` nor ends with `"/X"`. + +**Exemptions and blind spots**: keys that are not literals (variables, templates with expressions). A `Context.Service` assigned to a variable is not seen: see `service-not-as-class` (effecttsgo). `deterministic-keys` (effecttsgo) with the `default` or `package-identifier` formula produces keys this rule accepts; with `default-hashed` the two contradict each other: enable only one. + +**Why**: the key is the service's identity in errors, traces and `Context` lookups; a key that drifts from the name, as after a rename, makes it hard to find the class behind a message. + +**Options**: none + +**Fix**: suggestion that replaces the last segment of the key with the class name diff --git a/docs/user-guide/rules/service-port-shape-only.md b/docs/user-guide/rules/service-port-shape-only.md new file mode 100644 index 0000000..13b4158 --- /dev/null +++ b/docs/user-guide/rules/service-port-shape-only.md @@ -0,0 +1,27 @@ +--- +title: service-port-shape-only +group: Services and Layers +--- + +**Intent**: a port is a shape-only `Context.Service` (v3: `Context.Tag`), with no implementation attached. + +```ts +// ❌ no +class Agent extends Context.Service()("app/Agent", { make: makeAgent }) {} + +// ✅ yes +export class Agent extends Context.Service< + Agent, + { readonly search: (name: string) => Effect.Effect } +>()("app/agent/Agent") {} +``` + +**Trigger**: the second argument of `Context.Service<…>()(id, opts)`; a `static layer`, `static Default` or `static Live` member on a `Context.Service` or v3 `Context.Tag(id)<…>()` class; any `Effect.Service`. + +**Exemptions and blind spots**: a `Context.Service` or v3 `Context.GenericTag` assigned to a variable is not seen: see `service-not-as-class` (effecttsgo). Statics with other names slip through. + +**Why**: `make` and a static layer tie the port to a default implementation, while the port must stay a contract any adapter can satisfy. It is a convention, not Effect's idiom: Effect's own docs put `static readonly layer` on the service. + +**Options**: none + +**Fix**: none diff --git a/docs/user-guide/rules/single-style-per-function.md b/docs/user-guide/rules/single-style-per-function.md new file mode 100644 index 0000000..9880ab4 --- /dev/null +++ b/docs/user-guide/rules/single-style-per-function.md @@ -0,0 +1,36 @@ +--- +title: single-style-per-function +group: Effectful functions +--- + +**Intent**: a function is entirely Effect or not Effect at all. + +```ts +// ❌ no +export const POST = async (request: Request) => { + const form = await request.formData() + const created = await Effect.runPromise(Effect.result(createEvent(form))) + // … +} + +// ✅ yes: promises lifted with Effect.tryPromise +const createEvent = Effect.fn("events.create")(function* (request: Request) { + const form = yield* Effect.tryPromise({ + try: () => request.formData(), + catch: () => new BadRequest({ message: "invalid form data" }), + }) + // … +}) +``` + +**Trigger**: `async`, `await` and `.then(` in a function that builds Effects: an Effect generator, or a function using an `Effect.*` member. A `test`/`it` callback (`.only`, `.each(…)` and the like included) or a `beforeAll`/`afterAll`/`beforeEach`/`afterEach` hook, and in test files any other function except an Effect generator, is reported once, on the function, when more than one of its `await`s, or any `.then(`, involves Effect: has an `Effect.*` member in its expression, nested callbacks and `Effect.run*` included. + +**Exemptions and blind spots**: `Effect.run*` alone does not make a function effectful: it is how an async boundary hands over to Effect, and where it may appear is decided by [`run-only-in-runner`](run-only-in-runner.md). An `async` function that renders JSX itself, not only in nested callbacks, is a Server Component: how it turns failures into UI is left to the application. A test, hook or test helper may await promise-based fixtures (a container, an identity provider), then one Effect program, and assert on its result. A step that reaches Effect only through a helper (`await run(seed)`) is not counted. + +**Why**: errors travel on two channels, exceptions and Effect, and neither sees them all. + +**Options**: + +- `testFiles`: shared setting, see [Shared settings](../shared-settings.md). + +**Fix**: none diff --git a/docs/user-guide/rules/split-success-path-from-error-handling.md b/docs/user-guide/rules/split-success-path-from-error-handling.md new file mode 100644 index 0000000..39ed333 --- /dev/null +++ b/docs/user-guide/rules/split-success-path-from-error-handling.md @@ -0,0 +1,37 @@ +--- +title: split-success-path-from-error-handling +group: Error channel +--- + +**Intent**: the generator holds only the happy path; error handling lives in the second argument of `Effect.fn`. + +```ts +// ❌ no +function* () { + const x = yield* fetchThing.pipe(Effect.catchTag("NotFound", () => Effect.succeed(fallback))) +} + +// ✅ yes: naming the error or giving an alternative is not handling +function* () { + const x = yield* fetchThing.pipe(Effect.orElseSucceed(() => fallback)) + const y = yield* decode(raw).pipe(Effect.mapError((error) => new BadRequest({ message: error.message }))) +} + +// ✅ yes: translation in the second argument, which also receives the original arguments +const createEvent = Effect.fn("events.create")( + function* (request: Request) { /* success only */ }, + (effect, request) => effect.pipe(Effect.catchTags({ BadRequest: (e) => refused(400, e.message) })), +) +``` + +**Trigger**: inside a generator passed to `Effect.gen`/`Effect.fn`, callbacks passed to `Effect.*` combinators included, calls to `Effect.catch*` (`catch`, `catchAll`, `catchTag`, `catchTags`, `catchIf`, `catchCause`, `catchDefect`, `catchReason`, …), `either`, `result`, `exit`, `match*` and `sandbox`. + +**Exemptions and blind spots**: pipeables of a nested `Effect.fn`. Handlers inside the callback of an iteration (`forEach`, `filter`, `reduce`, `partition`, `validate`, `findFirst`, …): they handle each element on its own, and in the pipeables the first failure would stop the rest. Functions the generator only defines, such as an `HttpApiBuilder` handler or a service method: they are programs of their own. Test files, where the failure is the outcome under observation (`yield* Effect.result(op)` then `expect`). A `catch`, `catchTag`, `catchTags`, `catchIf` or `catchFilter` whose handlers only die (`Effect.die` passed directly or as the sole return): it is a selective `orDie`, declaring the case untracked rather than handling it; a die behind a wrapper or a condition is still reported. A `.pipe(Effect.catch…)` appended to an `Effect.gen` escapes; [`prefer-effect-fn`](prefer-effect-fn.md) closes that gap. + +**Why**: translation becomes a single exhaustive point instead of catches scattered along the flow. + +**Options**: + +- `testFiles`: shared setting, see [Shared settings](../shared-settings.md). + +**Fix**: none diff --git a/docs/user-guide/rules/try-object-form.md b/docs/user-guide/rules/try-object-form.md new file mode 100644 index 0000000..20af59d --- /dev/null +++ b/docs/user-guide/rules/try-object-form.md @@ -0,0 +1,27 @@ +--- +title: try-object-form +group: Error channel +--- + +**Intent**: `Effect.try` and `Effect.tryPromise` take `{ try, catch }`, with `catch` producing a tagged error. + +```ts +// ❌ no +Effect.tryPromise(() => api.spreadsheets.get({ spreadsheetId })) + +// ✅ yes +Effect.tryPromise({ + try: () => api.spreadsheets.get({ spreadsheetId }), + catch: toSheetError(spreadsheetId), +}) +``` + +**Trigger**: `Effect.try` and `Effect.tryPromise` whose argument is not an object literal. + +**Exemptions and blind spots**: an options object held in a variable is reported too. + +**Why**: the thunk form types the error as `Cause.UnknownError` (`UnknownException` in v3), which no caller can handle by tag. + +**Options**: none + +**Fix**: none diff --git a/docs/user-guide/rules/untraced-recursion.md b/docs/user-guide/rules/untraced-recursion.md new file mode 100644 index 0000000..8072175 --- /dev/null +++ b/docs/user-guide/rules/untraced-recursion.md @@ -0,0 +1,31 @@ +--- +title: untraced-recursion +group: Effectful functions +--- + +**Intent**: a recursive effectful function uses `Effect.fnUntraced`; the entry point that starts the recursion is traced. + +```ts +// ❌ no +const walk = Effect.fn("walk")(function* (node: Node) { + for (const child of node.children) yield* walk(child) +}) + +// ✅ yes +const walk = Effect.fnUntraced(function* (node: Node) { + for (const child of node.children) yield* walk(child) +}) +export const scan = Effect.fn("scan")(function* (root: Node) { + return yield* walk(root) +}) +``` + +**Trigger**: an `Effect.fn` assigned to a variable that its own body calls again, even by passing it as a callback. + +**Exemptions and blind spots**: mutual recursion, recursion in pipeables. + +**Why**: with `Effect.fn` every level opens a span nested in the previous one. + +**Options**: none + +**Fix**: none diff --git a/docs/user-guide/shared-settings.md b/docs/user-guide/shared-settings.md new file mode 100644 index 0000000..326267d --- /dev/null +++ b/docs/user-guide/shared-settings.md @@ -0,0 +1,59 @@ +--- +title: Shared settings +order: 3 +--- + +Three settings describe your project, not a rule, so they are declared once under `settings["dl-effect"]` in the oxlint config and every rule that uses them reads them from there. Their defaults fit a Node CLI; on another layout (Next.js, a monorepo) set them before reading the warnings. + +## The settings + +- **`entryFiles`**: the files allowed to run Effects and import adapters. + - used by: + - [`run-only-in-runner`](rules/run-only-in-runner.md) + - [`adapter-import-boundary`](rules/adapter-import-boundary.md) + - default: `**/main.ts`, `**/cli.ts`, `**/bin/**`. `index.ts` is excluded on purpose: it is usually a barrel, and exempting it would let adapters reach the rest of the application through re-exports. +- **`testFiles`**: the test files, exempt from the rules that tests legitimately break and the only files `prefer-effect-vitest` checks. + - used by: + - [`run-only-in-runner`](rules/run-only-in-runner.md), [`adapter-import-boundary`](rules/adapter-import-boundary.md), [`no-effect-promise`](rules/no-effect-promise.md), [`provide-named-layer`](rules/provide-named-layer.md), [`no-provide-on-definition`](rules/no-provide-on-definition.md), [`split-success-path-from-error-handling`](rules/split-success-path-from-error-handling.md), [`all-errors-handled-at-boundary`](rules/all-errors-handled-at-boundary.md), [`anti-slop-no-service-constructor-imports`](rules/anti-slop-no-service-constructor-imports.md): skip test files + - [`no-throw-or-primitive-failure`](rules/no-throw-or-primitive-failure.md): skips only primitive failures there + - [`single-style-per-function`](rules/single-style-per-function.md): treats their helpers like tests + - [`prefer-effect-vitest`](rules/prefer-effect-vitest.md): checks only them + - default: `**/*.test.*`, `**/*.spec.*`, `**/__tests__/**`, `**/test/**`, `**/tests/**`. A helper directory such as `src/testing/` does not count as tests: it is support code. +- **`discriminants`**: the fields that discriminate a closed union. + - used by: + - [`no-manual-discriminant-comparison`](rules/no-manual-discriminant-comparison.md) + - [`no-manual-discriminant-construction`](rules/no-manual-discriminant-construction.md) + - default: `_tag`. Add the fields your unions discriminate on, such as `type` or `kind`. + +File globs are matched against the path relative to oxlint's working directory, with `/` on every platform. + +## Setting a value + +Set one only where its default does not fit: it **replaces** the default instead of extending it. An unknown key or a value that is not an array of strings stops the lint with an error, so a typo is never silently ignored. + +```ts +import dlEffectAll from "@doubleloop-io/oxlint-plugin-effect/presets/all" +import { defineConfig } from "oxlint" + +export default defineConfig({ + extends: [dlEffectAll], + settings: { + "dl-effect": { entryFiles: ["apps/web/src/app/**/route.ts", "apps/web/src/runtime.ts"] }, + }, +}) +``` + +```json +{ + "extends": ["./node_modules/@doubleloop-io/oxlint-plugin-effect/dist/presets/all.json"], + "settings": { + "dl-effect": { "entryFiles": ["apps/web/src/app/**/route.ts", "apps/web/src/runtime.ts"] } + } +} +``` + +The package exports the defaults as `defaultEntryFiles`, `defaultTestFiles` and `defaultDiscriminants`: spread them to extend a default (`testFiles: [...defaultTestFiles, "e2e/**"]`). + +## Where settings go + +Settings belong to the config that lints: oxlint does not inherit them from a preset in `extends`, and rejects them in `overrides`. For a value that differs by group of files, use `overrides` on the rules instead. diff --git a/docs/user-guide/troubleshooting.md b/docs/user-guide/troubleshooting.md new file mode 100644 index 0000000..6ab029c --- /dev/null +++ b/docs/user-guide/troubleshooting.md @@ -0,0 +1,30 @@ +--- +title: Troubleshooting +order: 8 +--- + +The problems most often hit when adopting the plugin: each states the symptom, the cause and the fix. + +## The lint stops with a settings error + +- **Symptom**: oxlint exits with an error naming a `dl-effect` setting before reporting anything. +- **Cause**: a key under `settings["dl-effect"]` is not one of the shared settings, or its value is not an array of strings. +- **Fix**: correct the key or the value as described in [Shared settings](shared-settings.md#setting-a-value). + +## Settings are ignored or rejected + +- **Symptom**: settings put in a preset in `extends` have no effect, or oxlint rejects settings put in `overrides`. +- **Cause**: oxlint reads settings only from the config that lints. +- **Fix**: move them to that config, as described in [Where settings go](shared-settings.md#where-settings-go). + +## Many warnings on correct code + +- **Symptom**: on a layout that is not a Node CLI, such as Next.js or a monorepo, many warnings look like false positives, for example Effects run or adapters imported outside the entry files. +- **Cause**: the defaults of `entryFiles` and `testFiles` fit a Node CLI. +- **Fix**: set both for your layout, as described in [Shared settings](shared-settings.md#the-settings). + +## No warnings on code that uses aliases + +- **Symptom**: a file that breaks the rules gets no warnings. +- **Cause**: the rules recognize literal names only: see [Common limits](common-limits.md). +- **Fix**: import Effect modules under their own names where you want the rules to check the code. diff --git a/docs/user-guide/versioning.md b/docs/user-guide/versioning.md new file mode 100644 index 0000000..f6ee710 --- /dev/null +++ b/docs/user-guide/versioning.md @@ -0,0 +1,8 @@ +--- +title: Versioning +order: 7 +--- + +Versions are `0.x`: any minor release may add, remove or change rules, options, settings and messages. + +Supported oxlint is the `peerDependencies` range, `^1.82.0`; CI tests the tarball against `1.82.0`. oxlint's JS plugin API is still experimental, so a newer oxlint minor may break the plugin before the range is narrowed. diff --git a/package.json b/package.json index 7c808f3..d8ca575 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ }, "files": [ "dist/", - "RULES.md", + "docs/user-guide/", "README.md", "CHANGELOG.md", "LICENSE", @@ -35,7 +35,7 @@ "format:check": "oxfmt --check", "typecheck": "tsc --noEmit", "lint": "oxlint --deny-warnings", - "test": "node --test rules-md.test.ts rules/*.test.ts shared/*.test.ts scripts/*.test.ts", + "test": "node --test rule-files.test.ts rules/*.test.ts shared/*.test.ts scripts/*.test.ts", "check": "pnpm format:check && pnpm typecheck && pnpm lint && pnpm test", "build": "rm -rf dist && tsc -p tsconfig.build.json && node presets/all-json.ts", "build:w": "node --watch-path=index.ts --watch-path=rules --watch-path=presets --watch-path=shared --watch-path=tsconfig.build.json scripts/build.ts", diff --git a/rule-files.test.ts b/rule-files.test.ts new file mode 100644 index 0000000..e7c4647 --- /dev/null +++ b/rule-files.test.ts @@ -0,0 +1,18 @@ +import assert from "node:assert/strict" +import { readdir } from "node:fs/promises" +import { test } from "node:test" + +import dlEffectPlugin from "./index.ts" + +const ruleFileName = /^(?.+)\.md$/u + +const documentedRules = async () => { + const files = await readdir(new URL("docs/user-guide/rules/", import.meta.url)) + return files.flatMap((file) => ruleFileName.exec(file)?.groups?.rule ?? []).sort() +} + +test("the rule catalog has exactly one file per rule of the plugin", async () => { + const pluginRules = Object.keys(dlEffectPlugin.rules).sort() + + assert.deepEqual(await documentedRules(), pluginRules) +}) diff --git a/rules-md.test.ts b/rules-md.test.ts deleted file mode 100644 index 0920eb8..0000000 --- a/rules-md.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import assert from "node:assert/strict" -import { readFile } from "node:fs/promises" -import { test } from "node:test" - -import dlEffectPlugin from "./index.ts" - -const ruleHeading = /^### `([a-z-]+)`\n\n\[↑ rules index\]\(#rules-index\)<\/sup>$/gmu - -const documentedRules = async () => { - const rulesMd = await readFile(new URL("RULES.md", import.meta.url), "utf8") - return [...rulesMd.matchAll(ruleHeading)].map(([, rule]) => rule).sort() -} - -test("RULES.md has one section per rule of the plugin", async () => { - const pluginRules = Object.keys(dlEffectPlugin.rules).sort() - - assert.deepEqual(await documentedRules(), pluginRules) -}) diff --git a/scripts/pack-check.ts b/scripts/pack-check.ts index cd578c5..79b9c65 100644 --- a/scripts/pack-check.ts +++ b/scripts/pack-check.ts @@ -10,15 +10,8 @@ import { npmPack } from "./npm-pack.ts" const localPathMarkers = ["/Users/", "/home/"] // Mirrors `files` in package.json; npm adds package.json on its own. -const allowedFiles = [ - "package.json", - "RULES.md", - "README.md", - "CHANGELOG.md", - "LICENSE", - "LICENSE.anti-slop", -] -const allowedDirectories = ["dist/"] +const allowedFiles = ["package.json", "README.md", "CHANGELOG.md", "LICENSE", "LICENSE.anti-slop"] +const allowedDirectories = ["dist/", "docs/user-guide/"] const isAllowed = (path: string) => allowedFiles.includes(path) || diff --git a/tsconfig.json b/tsconfig.json index 30a8b56..25a3b06 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,7 +18,7 @@ "include": [ "index.ts", "oxlint.config.ts", - "rules-md.test.ts", + "rule-files.test.ts", "presets/**/*.ts", "rules/**/*.ts", "scripts/**/*.ts", diff --git a/website/astro.config.mjs b/website/astro.config.mjs index 7a20bc6..41430b4 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -2,8 +2,8 @@ import starlight from "@astrojs/starlight" import { defineConfig } from "astro/config" -import { publishedSite } from "./src/site-content/publishedSite.ts" -import { rulesOverviewId } from "./src/site-content/readmeMdSource.ts" +import { publishedSite, siteOrigin } from "./src/site-content/publishedSite.ts" +import { rulesOverviewId } from "./src/site-content/userGuideSource.ts" import { readSiteSources } from "./src/site-content/readSiteSources.ts" import { sitePages } from "./src/site-content/sitePages.ts" @@ -11,10 +11,9 @@ import { sitePages } from "./src/site-content/sitePages.ts" const pages = sitePages(await readSiteSources(new URL(".", import.meta.url)), publishedSite) const rulePages = pages.filter((page) => page.kind === "rule") const guidePages = pages.filter((page) => page.kind === "guide" && page.id !== rulesOverviewId) -const referencePages = pages.filter((page) => page.kind === "reference") export default defineConfig({ - site: "https://doubleloop-io.github.io", + site: siteOrigin, base: publishedSite.base, integrations: [ starlight({ @@ -45,7 +44,6 @@ export default defineConfig({ sidebar: [ { slug: "index", label: "Overview" }, ...guidePages.map(({ id }) => ({ slug: id })), - ...referencePages.map(({ id }) => ({ slug: id })), { label: "Rules", items: [ diff --git a/website/src/site-content/internalLinks.test.ts b/website/src/site-content/internalLinks.test.ts index 574d526..6095227 100644 --- a/website/src/site-content/internalLinks.test.ts +++ b/website/src/site-content/internalLinks.test.ts @@ -6,20 +6,16 @@ import { testSite } from "./sourceMarkdownBuilders.ts" const linkSource = (routes: Record): LinkSource => ({ ...testSite, - file: "RULES.md", - location: "rule `no-effect-promise`", + file: "docs/user-guide/shared-settings.md", routes: new Map(Object.entries(routes)), }) test("an anchor link points to its route under the base, also when the link names its file", () => { - const source = linkSource({ "RULES.md#try-object-form": "rules/try-object-form/" }) + const source = linkSource({ "docs/user-guide/shared-settings.md#defaults": "shared-settings/#defaults" }) - const body = rewriteInternalLinks( - "[a](#try-object-form), [b](RULES.md#try-object-form)", - source, - ) + const body = rewriteInternalLinks("[a](#defaults), [b](shared-settings.md#defaults)", source) - assert.equal(body, "[a](/site/rules/try-object-form/), [b](/site/rules/try-object-form/)") + assert.equal(body, "[a](/site/shared-settings/#defaults), [b](/site/shared-settings/#defaults)") }) test("links to the web and link-like text in a code block are left as they are", () => { @@ -32,7 +28,7 @@ test("links to the web and link-like text in a code block are left as they are", }) test("a link to a repository file with no site page points to the file on the main branch", () => { - const body = rewriteInternalLinks("See [the license](LICENSE.anti-slop).", linkSource({})) + const body = rewriteInternalLinks("See [the license](../../LICENSE.anti-slop).", linkSource({})) assert.equal(body, `See [the license](${testSite.repositoryUrl}/blob/main/LICENSE.anti-slop).`) }) diff --git a/website/src/site-content/internalLinks.ts b/website/src/site-content/internalLinks.ts index 27054b9..3cfc3c2 100644 --- a/website/src/site-content/internalLinks.ts +++ b/website/src/site-content/internalLinks.ts @@ -1,13 +1,14 @@ +import { posix } from "node:path" + import { markdownLines } from "./markdownLines.ts" import type { SiteOptions } from "./sitePages.ts" // Keyed by `#`, or by `` for the file itself, so one source can -// link into another (README → RULES.md) +// link into another (guide page → rule page) export type LinkRoutes = Map export type LinkSource = SiteOptions & { file: string - location: string routes: LinkRoutes } @@ -24,17 +25,22 @@ export const headingAnchor = (heading: string) => .replace(/[^\p{L}\p{N}\s-]/gu, "") .replace(/\s/gu, "-") +// A relative link is relative to the directory of the file it is in +const repositoryPath = (relativePath: string, { file }: LinkSource) => + posix.join(posix.dirname(file), relativePath) + export const resolveLink = (href: string, source: LinkSource) => { const target = internalHref.exec(href)?.groups if (target === undefined) { - return repositoryFileHref.test(href) ? `${source.repositoryUrl}/blob/main/${href}` : href + return repositoryFileHref.test(href) + ? `${source.repositoryUrl}/blob/main/${repositoryPath(href, source)}` + : href } - const { file = source.file, anchor } = target + const file = target.file === undefined ? source.file : repositoryPath(target.file, source) + const { anchor } = target const route = source.routes.get(anchor === undefined ? file : `${file}#${anchor}`) if (route === undefined) { - throw new Error( - `${source.file}, ${source.location}: link \`${href}\` resolves to no site page`, - ) + throw new Error(`${source.file}: link \`${href}\` resolves to no site page`) } return `${source.base.replace(/\/$/u, "")}/${route}` } diff --git a/website/src/site-content/publishedSite.ts b/website/src/site-content/publishedSite.ts index f38315f..dfa8200 100644 --- a/website/src/site-content/publishedSite.ts +++ b/website/src/site-content/publishedSite.ts @@ -1,5 +1,7 @@ import type { SiteOptions } from "./sitePages.ts" +export const siteOrigin = "https://doubleloop-io.github.io" + export const publishedSite = { base: "/oxlint-plugin-effect", repositoryUrl: "https://github.com/doubleloop-io/oxlint-plugin-effect", diff --git a/website/src/site-content/readSiteSources.ts b/website/src/site-content/readSiteSources.ts index 0cf4d53..ea6d9eb 100644 --- a/website/src/site-content/readSiteSources.ts +++ b/website/src/site-content/readSiteSources.ts @@ -1,8 +1,21 @@ -import { readFile } from "node:fs/promises" +import { readdir, readFile } from "node:fs/promises" -import type { SiteSources } from "./sitePages.ts" +import type { GuideFile, SiteSources } from "./sitePages.ts" +import { userGuideDirectory } from "./userGuideSource.ts" export const readSiteSources = async (siteRoot: URL): Promise => ({ - rulesMd: await readFile(new URL("../RULES.md", siteRoot), "utf8"), - readmeMd: await readFile(new URL("../README.md", siteRoot), "utf8"), + userGuide: await readUserGuide(new URL(`../${userGuideDirectory}/`, siteRoot)), }) + +export const readUserGuide = async (directory: URL) => { + const paths = await readdir(directory, { recursive: true }) + const markdownPaths = paths.filter((path) => path.endsWith(".md")).toSorted() + return Promise.all( + markdownPaths.map( + async (path): Promise => ({ + path: path.replaceAll("\\", "/"), + content: await readFile(new URL(path, directory), "utf8"), + }), + ), + ) +} diff --git a/website/src/site-content/readmeLinks.test.ts b/website/src/site-content/readmeLinks.test.ts new file mode 100644 index 0000000..b01a240 --- /dev/null +++ b/website/src/site-content/readmeLinks.test.ts @@ -0,0 +1,50 @@ +import assert from "node:assert/strict" +import { access, readFile } from "node:fs/promises" +import { test } from "node:test" + +import { markdownLinkHrefs } from "./internalLinks.ts" +import { publishedSite, siteOrigin } from "./publishedSite.ts" +import { readSiteSources } from "./readSiteSources.ts" +import { repositoryRoot } from "./realRepository.ts" +import { pageHeadingAnchors, routeOf } from "./siteLinkTargets.ts" +import { sitePages } from "./sitePages.ts" + +// The README is no site page: it reaches the guide through absolute URLs, which work on npmjs.com +const readmeHrefs = markdownLinkHrefs(await readFile(new URL("README.md", repositoryRoot), "utf8")) + +const pages = sitePages(await readSiteSources(new URL("website/", repositoryRoot)), publishedSite) +const { base, repositoryUrl } = publishedSite +const websiteUrl = `${siteOrigin}${base}/` +const repositoryFileUrl = `${repositoryUrl}/blob/main/` + +test("every link of the real README is an absolute URL to the website or to a repository file", () => { + const otherHrefs = readmeHrefs.filter( + (href) => !href.startsWith(websiteUrl) && !href.startsWith(repositoryFileUrl), + ) + + assert.ok(readmeHrefs.length > 0) + assert.deepEqual(otherHrefs, []) +}) + +test("every link of the real README to the website points to an existing site page and heading", () => { + const websiteHrefs = readmeHrefs.filter((href) => href.startsWith(websiteUrl)) + + assert.ok(websiteHrefs.length > 0) + for (const href of websiteHrefs) { + const [route, anchor] = href.replace(siteOrigin, "").split("#") + const target = pages.find(({ id }) => routeOf(id) === route) + assert.ok(target, `${href} is not a site page`) + if (anchor !== undefined) { + assert.ok(pageHeadingAnchors(target.body).includes(anchor), `${href} has no heading`) + } + } +}) + +test("every link of the real README to a repository file points to a file that exists", async () => { + const fileHrefs = readmeHrefs.filter((href) => href.startsWith(repositoryFileUrl)) + + for (const href of fileHrefs) { + const file = new URL(href.replace(repositoryFileUrl, ""), repositoryRoot) + await assert.doesNotReject(access(file), `${href} is not a repository file`) + } +}) diff --git a/website/src/site-content/readmeMdAlignment.test.ts b/website/src/site-content/readmeMdAlignment.test.ts deleted file mode 100644 index 94dc80c..0000000 --- a/website/src/site-content/readmeMdAlignment.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import assert from "node:assert/strict" -import { access, readFile } from "node:fs/promises" -import { test } from "node:test" - -import { headingAnchor, markdownLink, markdownLinkHrefs } from "./internalLinks.ts" -import { publishedSite } from "./publishedSite.ts" -import { maintainerSections, renamedSections } from "./readmeMdSource.ts" -import { expectedRulesMdRoute, repositoryRoot, rulesMarkdown } from "./realRulesMd.ts" -import { sitePages } from "./sitePages.ts" - -const readmeMarkdown = await readFile(new URL("README.md", repositoryRoot), "utf8") - -const { base, repositoryUrl } = publishedSite -const pages = sitePages({ rulesMd: rulesMarkdown, readmeMd: readmeMarkdown }, publishedSite) -const readmePages = pages.filter(({ kind }) => kind === "guide" || kind === "landing") - -// A README `##` section is a page, so its `###` subsections are `##` headings there -const withSubsectionsAtPageLevel = (text: string) => text.replace(/^### /gmu, "## ") - -const sectionHeadings = [...readmeMarkdown.matchAll(/^## (?.+)$/gmu)].map( - ({ groups }) => groups?.heading ?? "", -) -const publishedHeadings = sectionHeadings.filter((heading) => !maintainerSections.has(heading)) -const pageTitle = (heading: string) => renamedSections.get(heading)?.title ?? heading - -const sourceSection = (heading: string) => { - const start = readmeMarkdown.indexOf(`${heading}\n`) - const next = readmeMarkdown.slice(start + 1).search(/^## /mu) - const end = next === -1 ? undefined : start + 1 + next - return readmeMarkdown.slice(start, end).replace(`${heading}\n`, "").trim() -} - -const sectionRoutes = new Map( - publishedHeadings.flatMap((heading) => { - const route = heading === "Rules" ? "rules-overview/" : `${headingAnchor(heading)}/` - const subsectionRoutes = [...sourceSection(`## ${heading}`).matchAll(/^### (?.+)$/gmu)] - .map(({ groups }) => headingAnchor(groups?.sub ?? "")) - .map((anchor) => [anchor, `${route}#${anchor}`] as const) - return [[headingAnchor(heading), route] as const, ...subsectionRoutes] - }), -) - -const expectedHref = (href: string) => { - if (/^https?:/u.test(href)) return href - const link = /^(?[\w.-]+)?(?:#(?[\w-]+))?$/u.exec(href)?.groups - if (link?.file === "RULES.md") { - return `${base}/${link.anchor === undefined ? "rules-overview/" : expectedRulesMdRoute(link.anchor)}` - } - if (link?.file !== undefined) return `${repositoryUrl}/blob/main/${href}` - return `${base}/${sectionRoutes.get(link?.anchor ?? "") ?? "not-a-readme-section/"}` -} - -const pageText = (body: string) => body.trim() -const sourceText = (section: string) => - withSubsectionsAtPageLevel(section).replace( - markdownLink, - (_link, href: string) => `](${expectedHref(href)})`, - ) - -test("the real README introduction is the landing page with its text, links pointing to their page", () => { - const [title = ""] = readmeMarkdown.split("\n") - - const landing = pages.find(({ kind }) => kind === "landing") - - const [tagline, ...rest] = sourceText(sourceSection(title)).split("\n\n") - assert.ok(landing?.kind === "landing") - assert.equal(landing.title, title.replace(/^# /u, "")) - assert.equal(`${landing.scope ?? ""}${landing.name}`, landing.title) - assert.equal(landing.tagline, tagline) - assert.equal(pageText(landing.body), rest.join("\n\n")) -}) - -for (const heading of publishedHeadings) { - test(`the real README section ${heading} is a page with its text, links pointing to their page`, () => { - const page = readmePages.find(({ title }) => title === pageTitle(heading)) - - assert.equal(pageText(page?.body ?? ""), sourceText(sourceSection(`## ${heading}`))) - }) -} - -test("no page shows the Development section of the real README", () => { - const blocks = sourceSection("## Development") - .split("\n") - .filter((line) => line.startsWith("- ")) - - const shownBlocks = pages.flatMap((page) => - blocks.filter((block) => page.body.includes(block)).map((block) => `${page.id}: ${block}`), - ) - - assert.ok(blocks.length > 0) - assert.deepEqual(shownBlocks, []) -}) - -const routeOf = (id: string) => (id === "index" ? `${base}/` : `${base}/${id}/`) - -const pageHeadingAnchors = (body: string) => - [...body.matchAll(/^## (?.+)$/gmu)].map(({ groups }) => - headingAnchor(groups?.heading ?? ""), - ) - -const readmeHrefs = () => [ - ...readmePages.flatMap(({ body }) => markdownLinkHrefs(body)), - ...readmePages - .flatMap((page) => (page.kind === "landing" ? page.actions : [])) - .map(({ link }) => link), -] - -test("every internal link of the real README points to an existing site page and heading", () => { - const sitePageHrefs = readmeHrefs().filter((href) => href.startsWith(`${base}/`)) - - assert.ok(sitePageHrefs.length > 0) - for (const href of sitePageHrefs) { - const [route, anchor] = href.split("#") - const target = pages.find(({ id }) => routeOf(id) === route) - assert.ok(target, `${href} is not a site page`) - if (anchor !== undefined) { - assert.ok(pageHeadingAnchors(target.body).includes(anchor), `${href} has no heading`) - } - } -}) - -test("every link of the real README to a repository file points to a file that exists", async () => { - const fileHrefs = readmeHrefs().filter((href) => href.startsWith(`${repositoryUrl}/blob/main/`)) - - assert.ok(fileHrefs.length > 0) - for (const href of fileHrefs) { - const file = new URL(href.replace(`${repositoryUrl}/blob/main/`, ""), repositoryRoot) - await assert.doesNotReject(access(file), `${href} is not a repository file`) - } -}) diff --git a/website/src/site-content/readmeMdSource.test.ts b/website/src/site-content/readmeMdSource.test.ts deleted file mode 100644 index 74a09d2..0000000 --- a/website/src/site-content/readmeMdSource.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import assert from "node:assert/strict" -import { test } from "node:test" - -import { readmeMdSource } from "./readmeMdSource.ts" -import { readmeMarkdown } from "./sourceMarkdownBuilders.ts" - -const pagesOf = (readmeMd: string) => readmeMdSource(readmeMd).sourcePages.map(({ page }) => page) - -const pageById = (readmeMd: string, id: string) => pagesOf(readmeMd).find((page) => page.id === id) - -test("each section of the README becomes a page named after its heading, in README order", () => { - const readmeMd = readmeMarkdown( - "## Installation\n\n```bash\npnpm add -D the-plugin\n```\n", - "## Versioning\n\nVersions are `0.x`.\n", - ) - - const pages = pagesOf(readmeMd).filter(({ kind }) => kind === "guide") - - assert.deepEqual(pages, [ - { - kind: "guide", - id: "installation", - title: "Installation", - body: "```bash\npnpm add -D the-plugin\n```\n", - }, - { kind: "guide", id: "versioning", title: "Versioning", body: "Versions are `0.x`.\n" }, - ]) -}) - -test("a subsection stays on the page of its section, one heading level up", () => { - const readmeMd = readmeMarkdown( - "## Configuration\n\nExtend the preset.\n\n### Configuration options\n\nThree settings.\n", - ) - - const page = pageById(readmeMd, "configuration") - - assert.equal(page?.body, "Extend the preset.\n\n## Configuration options\n\nThree settings.\n") -}) - -test("the Rules section is the rules overview page", () => { - const readmeMd = readmeMarkdown( - "## Rules\n\n| Topic | Rules |\n\n### Absorbed from anti-slop\n\nSome rules.\n", - ) - - const page = pageById(readmeMd, "rules-overview") - - assert.deepEqual(page, { - kind: "guide", - id: "rules-overview", - title: "Rules overview", - body: "| Topic | Rules |\n\n## Absorbed from anti-slop\n\nSome rules.\n", - }) -}) - -test("the Development section and its subsections are on no page", () => { - const readmeMd = readmeMarkdown( - "## Versioning\n\nVersions are `0.x`.\n", - "## Development\n\n- `pnpm format`: formats.\n\n### Releasing\n\n- `pnpm release`.\n", - ) - - const pages = pagesOf(readmeMd) - - assert.ok(!pages.some(({ id }) => id === "development")) - assert.ok(!pages.some(({ body }) => body.includes("pnpm format") || body.includes("Releasing"))) -}) - -test("an unscoped package name is the whole landing title, and an introduction of one paragraph leaves an empty body", () => { - const page = pageById(readmeMarkdown(), "index") - - assert.ok(page?.kind === "landing") - assert.equal(page.scope, undefined) - assert.equal(page.name, "the-plugin") - assert.equal(page.tagline, "A plugin.") - assert.equal(page.body, "") -}) diff --git a/website/src/site-content/readmeMdSource.ts b/website/src/site-content/readmeMdSource.ts deleted file mode 100644 index 5594de9..0000000 --- a/website/src/site-content/readmeMdSource.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { headingAnchor } from "./internalLinks.ts" -import { markdownLines } from "./markdownLines.ts" -import type { SitePage, SourcePage } from "./sitePages.ts" - -type Section = { level: "#" | "##"; heading: string; subheadings: string[]; lines: string[] } - -const file = "README.md" - -const sectionHeading = /^(?##?) (?.+)$/u -const subsectionHeading = /^### (?<title>.+)$/u - -// Addressed to the plugin maintainers, not to its users -export const maintainerSections = new Set(["Development"]) - -export const rulesOverviewId = "rules-overview" - -// `rules/` is the parent route of the rule pages -export const renamedSections = new Map([["Rules", { id: rulesOverviewId, title: "Rules overview" }]]) - -const guidePage = (heading: string) => - renamedSections.get(heading) ?? { id: headingAnchor(heading), title: heading } - -const landingActions = [ - { text: "Installation", link: "#installation" }, - { text: "Rules overview", link: "RULES.md" }, -] - -export const readmeMdSource = (markdown: string) => { - const readmeSections = sections(markdown).filter( - ({ heading }) => !maintainerSections.has(heading), - ) - const sourcePages = readmeSections.map(readmeMdPage) - return { sourcePages, routes: linkRoutes(readmeSections) } -} - -const packageName = /^(?<scope>@[^/]+\/)?(?<name>.+)$/u - -const readmeMdPage = ({ level, heading, lines }: Section): SourcePage => { - const body = `${lines.join("\n").trim()}\n` - return level === "#" - ? { page: landingPage(heading, body), file, location: "introduction" } - : { - page: { kind: "guide", ...guidePage(heading), body }, - file, - location: `section \`${heading}\``, - } -} - -// The heading is the package name, split so the scope can sit above the name; -// the first paragraph is the tagline under it, so the body starts after it -const landingPage = (heading: string, introduction: string): SitePage => { - const { scope, name = heading } = packageName.exec(heading)?.groups ?? {} - const [tagline = "", ...rest] = introduction.split("\n\n") - const body = rest.length === 0 ? "" : `${rest.join("\n\n").trim()}\n` - return { kind: "landing", id: "index", title: heading, scope, name, tagline: tagline.trim(), body, actions: landingActions } -} - -const linkRoutes = (readmeSections: Section[]) => - new Map( - readmeSections - .filter(({ level }) => level === "##") - .flatMap(({ heading, subheadings }) => { - const route = `${guidePage(heading).id}/` - return [ - [`${file}#${headingAnchor(heading)}`, route] as const, - ...subheadings.map( - (subheading) => - [ - `${file}#${headingAnchor(subheading)}`, - `${route}#${headingAnchor(subheading)}`, - ] as const, - ), - ] - }), - ) - -// A section is a page whose title is the `##` heading, so its `###` subsections become `##` -const sections = (markdown: string) => { - const found: Section[] = [] - let current: Section | undefined - for (const { line, insideCodeBlock } of markdownLines(markdown.split("\n"))) { - const heading = insideCodeBlock ? undefined : sectionHeading.exec(line)?.groups - const subheading = insideCodeBlock ? undefined : subsectionHeading.exec(line)?.groups?.title - if (heading?.title !== undefined) { - const level = heading.level === "#" ? "#" : "##" - current = { level, heading: heading.title, subheadings: [], lines: [] } - found.push(current) - } else if (subheading !== undefined) { - current?.subheadings.push(subheading) - current?.lines.push(`## ${subheading}`) - } else { - current?.lines.push(line) - } - } - return found -} diff --git a/website/src/site-content/realRepository.ts b/website/src/site-content/realRepository.ts new file mode 100644 index 0000000..6e7c0e6 --- /dev/null +++ b/website/src/site-content/realRepository.ts @@ -0,0 +1 @@ +export const repositoryRoot = new URL("../../../", import.meta.url) diff --git a/website/src/site-content/realRulesMd.ts b/website/src/site-content/realRulesMd.ts deleted file mode 100644 index 50b91d5..0000000 --- a/website/src/site-content/realRulesMd.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { readFile } from "node:fs/promises" - -export const repositoryRoot = new URL("../../../", import.meta.url) - -export const rulesMarkdown = await readFile(new URL("RULES.md", repositoryRoot), "utf8") - -export const rulesIndexRow = - /^\| (?:\[(?<group>[^\]]+)\]\(#(?<groupAnchor>[a-z-]+)\))? +\| \[`(?<rule>[a-z-]+)`\]/gmu - -// A group's row in the rules index names its first rule -const firstRuleOfGroup = new Map( - [...rulesMarkdown.matchAll(rulesIndexRow)].flatMap(({ groups }) => - groups?.groupAnchor === undefined ? [] : [[groups.groupAnchor, groups.rule] as const], - ), -) - -const referencePageRoutes = new Map([ - ["rules-index", "rules-overview/"], - ["common-limits", "common-limits/"], - ["shared-settings", "shared-settings/"], -]) - -// The route a test expects for a RULES.md anchor, stated apart from how the site derives it -export const expectedRulesMdRoute = (anchor: string) => - referencePageRoutes.get(anchor) ?? `rules/${firstRuleOfGroup.get(anchor) ?? anchor}/` diff --git a/website/src/site-content/rulePages.test.ts b/website/src/site-content/rulePages.test.ts new file mode 100644 index 0000000..ab905d0 --- /dev/null +++ b/website/src/site-content/rulePages.test.ts @@ -0,0 +1,173 @@ +import assert from "node:assert/strict" +import { test } from "node:test" + +import { ruleBody, ruleFile, rulePagesOf, rulesIndexFile } from "./sourceMarkdownBuilders.ts" + +test("a rule file is a rule page named after the rule, in the group of its frontmatter, with the file body", () => { + const userGuide = [ + rulesIndexFile("no-effect-promise"), + ruleFile("no-effect-promise", { group: "Error channel" }), + ] + + const pages = rulePagesOf(userGuide) + + assert.deepEqual(pages, [ + { + kind: "rule", + id: "rules/no-effect-promise", + title: "no-effect-promise", + group: "Error channel", + body: ruleBody(), + }, + ]) +}) + +for (const [field, label] of [ + ["intent", "Intent"], + ["trigger", "Trigger"], + ["options", "Options"], + ["fix", "Fix"], +] as const) { + test(`a rule file without ${label} fails the build, naming the file and the field`, () => { + const userGuide = [ + rulesIndexFile("no-effect-promise"), + ruleFile("no-effect-promise", { fields: { [field]: null } }), + ] + + assert.throws(() => rulePagesOf(userGuide), { + message: `docs/user-guide/rules/no-effect-promise.md: missing **${label}**`, + }) + }) +} + +for (const [scenario, fields, problem] of [ + [ + "a Fix other than none, autofix or a suggestion", + { fix: "**Fix**: sometimes" }, + "**Fix** is not none, autofix or suggestion", + ], + [ + "Options that are neither none nor a list", + { options: "**Options**: a few." }, + "**Options** is neither none nor followed by a list", + ], + [ + "an example that does not open with the reported form", + { example: "```ts\n// ✅ yes\nright()\n\n// ❌ no\nwrong()\n```" }, + "the example does not start with `// ❌ no`", + ], + [ + "an example marking its forms without emoji", + { example: "```ts\n// no\nwrong()\n\n// yes\nright()\n```" }, + "the example does not start with `// ❌ no`", + ], + [ + "an example with no compliant form", + { example: "```ts\n// ❌ no\nwrong()\n```" }, + "the example has no `// ✅ yes`", + ], +] as const) { + test(`a rule file with ${scenario} fails the build, naming the file`, () => { + const userGuide = [rulesIndexFile("no-effect-promise"), ruleFile("no-effect-promise", { fields })] + + assert.throws(() => rulePagesOf(userGuide), { + message: `docs/user-guide/rules/no-effect-promise.md: ${problem}`, + }) + }) +} + +test("Options followed by a list and a suggestion Fix with its detail follow the template", () => { + const userGuide = [ + rulesIndexFile("no-effect-promise"), + ruleFile("no-effect-promise", { + fields: { + options: "**Options**:\n\n- `testFiles`: shared setting.", + fix: "**Fix**: suggestion that wraps the literal", + }, + }), + ] + + const pages = rulePagesOf(userGuide) + + assert.equal(pages.length, 1) +}) + +test("a sibling rule may leave the example, Exemptions and Why to the rule it links to", () => { + const userGuide = [ + rulesIndexFile("try-object-form"), + ruleFile("try-object-form", { fields: { example: null, exemptions: null, why: null } }), + ] + + const pages = rulePagesOf(userGuide) + + assert.deepEqual( + pages.map(({ id }) => id), + ["rules/try-object-form"], + ) +}) + +test("a heading-like line inside a code example stays in the rule body", () => { + const example = "```ts\n// ❌ no\n## not a heading\nwrong()\n\n// ✅ yes\nright()\n```" + const userGuide = [ + rulesIndexFile("no-effect-promise"), + ruleFile("no-effect-promise", { fields: { example } }), + ] + + const [page] = rulePagesOf(userGuide) + + assert.match(page?.body ?? "", /## not a heading/u) +}) + +test("a rule file without a group fails the build, naming the file", () => { + const userGuide = [ + rulesIndexFile("no-effect-promise"), + { + path: "rules/no-effect-promise.md", + content: `---\ntitle: no-effect-promise\n---\n\n${ruleBody()}`, + }, + ] + + assert.throws(() => rulePagesOf(userGuide), { + message: "docs/user-guide/rules/no-effect-promise.md: frontmatter has no `group`", + }) +}) + +test("rule pages follow the order of their links in the rules index, whatever the file order", () => { + const userGuide = [ + ruleFile("try-object-form", { group: "Error channel" }), + ruleFile("no-nested-match", { group: "Code shape" }), + ruleFile("no-effect-promise", { group: "Error channel" }), + rulesIndexFile("no-effect-promise", "try-object-form", "no-nested-match"), + ] + + const ids = rulePagesOf(userGuide).map(({ id }) => id) + + assert.deepEqual(ids, [ + "rules/no-effect-promise", + "rules/try-object-form", + "rules/no-nested-match", + ]) +}) + +test("a rule file the rules index does not link fails the build, naming the file", () => { + const userGuide = [ + rulesIndexFile("no-effect-promise"), + ruleFile("no-effect-promise"), + ruleFile("try-object-form"), + ] + + assert.throws(() => rulePagesOf(userGuide), { + message: + "docs/user-guide/rules/try-object-form.md: not linked from the rules index, docs/user-guide/rules.md", + }) +}) + +test("a guide file outside the rule directory with a group fails the build, naming the file", () => { + const userGuide = [ + { path: "versioning.md", content: "---\ntitle: Versioning\ngroup: Misc\n---\n\nText.\n" }, + ] + + assert.throws(() => rulePagesOf(userGuide), { + message: "docs/user-guide/versioning.md: frontmatter has unknown field `group`", + }) +}) diff --git a/website/src/site-content/ruleTemplate.ts b/website/src/site-content/ruleTemplate.ts new file mode 100644 index 0000000..a6198c9 --- /dev/null +++ b/website/src/site-content/ruleTemplate.ts @@ -0,0 +1,47 @@ +import { isCodeFence, markdownLines } from "./markdownLines.ts" + +const requiredFields = ["Intent", "Trigger", "Options", "Fix"] +const fieldLabel = /^\*\*(?<label>[^*]+)\*\*:/u + +// What breaks the catalog template in a rule file body, undefined when it follows the template +export const ruleTemplateProblem = (body: string) => { + const lines = body.split("\n") + const prose = proseLines(lines) + const fields = new Map( + prose.flatMap((line, index) => { + const label = fieldLabel.exec(line)?.groups?.label + const value = line.replace(fieldLabel, "").trim() + return label === undefined ? [] : [[label, { value, index }] as const] + }), + ) + const missing = requiredFields.find((field) => !fields.has(field)) + if (missing !== undefined) return `missing **${missing}**` + + if (!fixValue.test(fields.get("Fix")?.value ?? "")) { + return "**Fix** is not none, autofix or suggestion" + } + const options = fields.get("Options") + const lineAfterOptions = prose.slice((options?.index ?? 0) + 1).find((line) => line !== "") + const optionsAreListed = options?.value === "" && lineAfterOptions?.startsWith("- ") + if (options?.value !== "none" && !optionsAreListed) { + return "**Options** is neither none nor followed by a list" + } + return exampleProblem(lines) +} + +const fixValue = /^(none|autofix|suggestion\b)/u + +const exampleProblem = (lines: string[]) => { + const start = lines.findIndex(isCodeFence) + if (start === -1) return undefined + const end = lines.findIndex((line, index) => index > start && isCodeFence(line)) + const example = lines.slice(start + 1, end) + if (!example[0]?.startsWith("// ❌ no")) return "the example does not start with `// ❌ no`" + if (!example.some((line) => line.startsWith("// ✅ yes"))) return "the example has no `// ✅ yes`" + return undefined +} + +const proseLines = (lines: string[]) => + markdownLines(lines).map(({ line, isFence, insideCodeBlock }) => + insideCodeBlock || isFence ? "```" : line, + ) diff --git a/website/src/site-content/rulesMdAlignment.test.ts b/website/src/site-content/rulesMdAlignment.test.ts deleted file mode 100644 index 46a3d40..0000000 --- a/website/src/site-content/rulesMdAlignment.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import assert from "node:assert/strict" -import { access, readFile } from "node:fs/promises" -import { test } from "node:test" - -import { markdownLink, markdownLinkHrefs } from "./internalLinks.ts" -import { publishedSite } from "./publishedSite.ts" -import { - expectedRulesMdRoute, - repositoryRoot, - rulesIndexRow, - rulesMarkdown, -} from "./realRulesMd.ts" -import { backLink } from "./rulesMdSource.ts" -import { sitePages } from "./sitePages.ts" - -const readmeMarkdown = await readFile(new URL("README.md", repositoryRoot), "utf8") - -const { base, repositoryUrl } = publishedSite -const pages = sitePages({ rulesMd: rulesMarkdown, readmeMd: readmeMarkdown }, publishedSite) -const rulePages = () => pages.filter((page) => page.kind === "rule") -const rulesMdPages = () => pages.filter(({ kind }) => kind === "rule" || kind === "reference") - -const ruleHeadingAndNextLine = /^### `(?<rule>[a-z-]+)`\n\n(?<nextLine>.*)$/gmu - -const rulesIndex = () => { - let group = "" - return [...rulesMarkdown.matchAll(rulesIndexRow)].map((row) => { - group = row.groups?.group ?? group - return { id: `rules/${row.groups?.rule}`, group } - }) -} - -const expectedHref = (href: string) => { - const anchor = /^#(?<anchor>[a-z-]+)$/u.exec(href)?.groups?.anchor - if (anchor !== undefined) return `${base}/${expectedRulesMdRoute(anchor)}` - return /^https?:/u.test(href) ? href : `${repositoryUrl}/blob/main/${href}` -} - -const withExpectedHrefs = (text: string) => - text.replace(markdownLink, (_link, href: string) => `](${expectedHref(href)})`) - -const sourceSection = (heading: string) => { - const start = rulesMarkdown.indexOf(`${heading}\n`) - const next = rulesMarkdown.slice(start + 1).search(/^##+ /mu) - return rulesMarkdown.slice(start, next === -1 ? undefined : start + 1 + next) -} - -test("the site has exactly one page per rule section of the real RULES.md", () => { - const documentedRules = [...rulesMarkdown.matchAll(ruleHeadingAndNextLine)] - .filter(({ groups }) => groups?.nextLine === backLink) - .map(({ groups }) => `rules/${groups?.rule}`) - - const pageIds = rulePages().map(({ id }) => id) - - assert.deepEqual(pageIds, documentedRules) -}) - -test("rule pages sit in the group of their section, in the order of the real rules index", () => { - const pages = rulePages() - - assert.deepEqual( - pages.map(({ id, group }) => ({ id, group })), - rulesIndex(), - ) -}) - -test("every block of a real RULES.md rule section is on its page, links pointing to the page of their anchor", () => { - for (const page of rulePages()) { - const blocks = sourceSection(`### \`${page.title}\``) - .split("\n\n") - .slice(1) - .map((block) => block.trim()) - .filter((block) => block !== backLink && block !== "") - - for (const block of blocks) { - assert.ok(page.body.includes(withExpectedHrefs(block)), `${page.id}: ${block}`) - } - assert.ok(!page.body.includes(backLink), `${page.id} shows the back link`) - } -}) - -for (const heading of ["Common limits", "Shared settings"]) { - test(`${heading} is a page with the text of its real RULES.md section, links pointing to the page of their anchor`, () => { - const source = sourceSection(`## ${heading}`).replace(`## ${heading}\n`, "").trim() - - const page = pages.find(({ title }) => title === heading) - - assert.equal(page?.body.trim(), withExpectedHrefs(source)) - }) -} - -test("every link between sections of the real RULES.md points to an existing site page", () => { - const routes = new Set(pages.map(({ id }) => `${base}/${id}/`)) - - const hrefs = rulesMdPages().flatMap(({ body }) => markdownLinkHrefs(body)) - - const sitePageHrefs = hrefs.filter((href) => href.startsWith(`${base}/`)) - assert.ok(sitePageHrefs.length > 0) - for (const href of sitePageHrefs) assert.ok(routes.has(href), `${href} is not a site page`) -}) - -// RULES.md links to no repository file today, so this guards the links it may gain -test("every link of the real RULES.md to a repository file points to a file that exists", async () => { - const fileHrefs = rulesMdPages() - .flatMap(({ body }) => markdownLinkHrefs(body)) - .filter((href) => href.startsWith(`${repositoryUrl}/blob/main/`)) - - for (const href of fileHrefs) { - const file = new URL(href.replace(`${repositoryUrl}/blob/main/`, ""), repositoryRoot) - await assert.doesNotReject(access(file), `${href} is not a repository file`) - } -}) diff --git a/website/src/site-content/rulesMdSource.test.ts b/website/src/site-content/rulesMdSource.test.ts deleted file mode 100644 index 796ed72..0000000 --- a/website/src/site-content/rulesMdSource.test.ts +++ /dev/null @@ -1,187 +0,0 @@ -import assert from "node:assert/strict" -import { test } from "node:test" - -import { rulesMdSource } from "./rulesMdSource.ts" -import { group, ruleSection, rulesMarkdown, wellFormedFields } from "./sourceMarkdownBuilders.ts" - -const pagesOf = (markdown: string) => rulesMdSource(markdown).sourcePages.map(({ page }) => page) - -const rulePages = (markdown: string) => pagesOf(markdown).filter((page) => page.kind === "rule") - -test("each rule section becomes a page named after the rule, in the group of its section", () => { - const markdown = rulesMarkdown( - group("Error channel", ruleSection("no-effect-promise"), ruleSection("try-object-form")), - group("Tagged values", ruleSection("no-manual-discriminant-comparison")), - ) - - const pages = rulePages(markdown) - - assert.deepEqual( - pages.map(({ id, title, group }) => ({ id, title, group })), - [ - { id: "rules/no-effect-promise", title: "no-effect-promise", group: "Error channel" }, - { id: "rules/try-object-form", title: "try-object-form", group: "Error channel" }, - { - id: "rules/no-manual-discriminant-comparison", - title: "no-manual-discriminant-comparison", - group: "Tagged values", - }, - ], - ) -}) - -test("a rule page carries the section body without the back link to the rules index", () => { - const markdown = rulesMarkdown( - group( - "Error channel", - ruleSection("no-effect-promise", { intent: "**Intent**: lift with tryPromise." }), - ), - ) - - const [page] = rulePages(markdown) - - assert.equal( - page?.body, - [ - "**Intent**: lift with tryPromise.", - wellFormedFields.example, - wellFormedFields.trigger, - wellFormedFields.exemptions, - wellFormedFields.why, - wellFormedFields.options, - wellFormedFields.fix, - ].join("\n\n") + "\n", - ) -}) - -test("a heading-like line inside a code example stays in the rule body", () => { - const example = "```ts\n// no\n## not a heading\nwrong()\n\n// yes\nright()\n```" - const markdown = rulesMarkdown( - group("Error channel", ruleSection("no-effect-promise", { example })), - ) - - const [page] = rulePages(markdown) - - assert.match(page?.body ?? "", /## not a heading/u) -}) - -for (const [field, label] of [ - ["intent", "Intent"], - ["trigger", "Trigger"], - ["options", "Options"], - ["fix", "Fix"], -] as const) { - test(`a rule section without ${label} fails, naming the rule and the field`, () => { - const markdown = rulesMarkdown( - group("Error channel", ruleSection("no-effect-promise", { [field]: null })), - ) - - assert.throws(() => rulesMdSource(markdown), { - message: `RULES.md, rule \`no-effect-promise\`: missing **${label}**`, - }) - }) -} - -for (const [scenario, fields, problem] of [ - [ - "a Fix other than none, autofix or a suggestion", - { fix: "**Fix**: sometimes" }, - "**Fix** is not none, autofix or suggestion", - ], - [ - "Options that are neither none nor a list", - { options: "**Options**: a few." }, - "**Options** is neither none nor followed by a list", - ], - [ - "an example that does not open with the reported form", - { example: "```ts\n// yes\nright()\n\n// no\nwrong()\n```" }, - "the example does not start with `// no`", - ], - [ - "an example with no compliant form", - { example: "```ts\n// no\nwrong()\n```" }, - "the example has no `// yes`", - ], -] as const) { - test(`a rule section with ${scenario} fails, naming the rule`, () => { - const markdown = rulesMarkdown( - group("Error channel", ruleSection("no-effect-promise", fields)), - ) - - assert.throws(() => rulesMdSource(markdown), { - message: `RULES.md, rule \`no-effect-promise\`: ${problem}`, - }) - }) -} - -test("Options followed by a list and a suggestion Fix with its detail follow the template", () => { - const markdown = rulesMarkdown( - group( - "Error channel", - ruleSection("no-effect-promise", { - options: "**Options**:\n\n- `testFiles`: shared setting.", - fix: "**Fix**: suggestion that wraps the literal", - }), - ), - ) - - const pages = rulePages(markdown) - - assert.equal(pages.length, 1) -}) - -test("a sibling rule may leave the example, Exemptions and Why to the rule it links to", () => { - const markdown = rulesMarkdown( - group( - "Error channel", - ruleSection("try-object-form", { example: null, exemptions: null, why: null }), - ), - ) - - const pages = rulePages(markdown) - - assert.deepEqual( - pages.map(({ id }) => id), - ["rules/try-object-form"], - ) -}) - -const pageById = (markdown: string, id: string) => pagesOf(markdown).find((page) => page.id === id) - -test("Shared settings and Common limits each become a page with the body of their section", () => { - const markdown = rulesMarkdown( - "## Common limits\n\n- **Syntax only**: no type information.\n", - "## Shared settings\n\nDeclared once.\n\n- **`testFiles`**: test globs.\n", - group("Error channel", ruleSection("no-effect-promise")), - ) - - const pages = [pageById(markdown, "common-limits"), pageById(markdown, "shared-settings")] - - assert.deepEqual(pages, [ - { - kind: "reference", - id: "common-limits", - title: "Common limits", - body: "- **Syntax only**: no type information.\n", - }, - { - kind: "reference", - id: "shared-settings", - title: "Shared settings", - body: "Declared once.\n\n- **`testFiles`**: test globs.\n", - }, - ]) -}) - -test("the rules index has no page, as the rules overview lists every rule", () => { - const markdown = [ - "# Rules\n", - "## Rules index\n\n| Group | Rule |\n| --- | --- |\n\nAll at `warn`.\n", - group("Error channel", ruleSection("no-effect-promise")), - ].join("\n") - - const pages = rulesMdSource(markdown).sourcePages - - assert.ok(pages.every(({ page }) => page.title !== "Rules index")) -}) diff --git a/website/src/site-content/rulesMdSource.ts b/website/src/site-content/rulesMdSource.ts deleted file mode 100644 index 1a1c0d4..0000000 --- a/website/src/site-content/rulesMdSource.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { headingAnchor } from "./internalLinks.ts" -import { isCodeFence, markdownLines } from "./markdownLines.ts" -import { rulesOverviewId } from "./readmeMdSource.ts" -import type { SitePage, SourcePage } from "./sitePages.ts" - -type Section = { - heading: string - group: string - lines: string[] -} - -type RuleSection = Section & { name: string } - -const file = "RULES.md" - -const referencePageIds = new Map([ - ["Common limits", "common-limits"], - ["Shared settings", "shared-settings"], -]) - -const sectionHeading = /^(?<level>#{1,3}) (?<title>.+)$/u -const ruleHeading = /^`(?<name>[a-z-]+)`$/u - -export const backLink = "<sup>[↑ rules index](#rules-index)</sup>" - -const requiredFields = ["Intent", "Trigger", "Options", "Fix"] -const fieldLabel = /^\*\*(?<label>[^*]+)\*\*:/u - -export const rulesMdSource = (markdown: string) => { - const allSections = sections(markdown) - const rulesMdPages = allSections.flatMap(rulesMdPage) - return { - sourcePages: rulesMdPages.map(({ heading: _, ...source }) => source), - routes: linkRoutes(allSections, rulesMdPages), - } -} - -type RulesMdPage = SourcePage & { heading: string } - -const rulesMdPage = (section: Section): RulesMdPage[] => { - const { heading } = section - const name = ruleHeading.exec(heading)?.groups?.name - if (name !== undefined) { - const page = rulePage({ ...section, name }) - return [{ page, file, heading, location: `rule \`${name}\`` }] - } - const id = referencePageIds.get(heading) - if (id === undefined) return [] - const page: SitePage = { kind: "reference", id, title: heading, body: body(section) } - return [{ page, file, heading, location: `section \`${heading}\`` }] -} - -// The README Rules section lists every rule, so it stands in for the rules index, which has no page -const rulesIndexRoute = `${rulesOverviewId}/` - -// A group has no page: its anchor leads to its first rule, as its heading does in RULES.md -const linkRoutes = (allSections: Section[], sourcePages: RulesMdPage[]) => - new Map([ - [file, rulesIndexRoute], - [`${file}#rules-index`, rulesIndexRoute], - ...allSections.flatMap(({ heading }): [string, string][] => { - const target = - sourcePages.find((source) => source.heading === heading)?.page ?? - sourcePages.find(({ page }) => page.kind === "rule" && page.group === heading)?.page - return target === undefined - ? [] - : [[`${file}#${headingAnchor(heading)}`, `${target.id}/`]] - }), - ]) - -const rulePage = (section: RuleSection): SitePage => { - assertFollowsCatalogTemplate(section) - return { - kind: "rule", - id: `rules/${section.name}`, - title: section.name, - group: section.group, - body: body(section), - } -} - -const body = ({ lines }: Section) => `${lines.join("\n").trim()}\n` - -const assertFollowsCatalogTemplate = ({ name, lines }: RuleSection) => { - const problem = templateProblem(lines) - if (problem !== undefined) throw new Error(`RULES.md, rule \`${name}\`: ${problem}`) -} - -const templateProblem = (lines: string[]) => { - const prose = proseLines(lines) - const fields = new Map( - prose.flatMap((line, index) => { - const label = fieldLabel.exec(line)?.groups?.label - const value = line.replace(fieldLabel, "").trim() - return label === undefined ? [] : [[label, { value, index }] as const] - }), - ) - const missing = requiredFields.find((field) => !fields.has(field)) - if (missing !== undefined) return `missing **${missing}**` - - if (!fixValue.test(fields.get("Fix")?.value ?? "")) { - return "**Fix** is not none, autofix or suggestion" - } - const options = fields.get("Options") - const lineAfterOptions = prose.slice((options?.index ?? 0) + 1).find((line) => line !== "") - const optionsAreListed = options?.value === "" && lineAfterOptions?.startsWith("- ") - if (options?.value !== "none" && !optionsAreListed) { - return "**Options** is neither none nor followed by a list" - } - return exampleProblem(lines) -} - -const fixValue = /^(none|autofix|suggestion\b)/u - -const exampleProblem = (lines: string[]) => { - const start = lines.findIndex(isCodeFence) - if (start === -1) return undefined - const end = lines.findIndex((line, index) => index > start && isCodeFence(line)) - const example = lines.slice(start + 1, end) - if (!example[0]?.startsWith("// no")) return "the example does not start with `// no`" - if (!example.some((line) => line.startsWith("// yes"))) return "the example has no `// yes`" - return undefined -} - -const proseLines = (lines: string[]) => - markdownLines(lines).map(({ line, isFence, insideCodeBlock }) => - insideCodeBlock || isFence ? "```" : line, - ) - -const sections = (markdown: string) => { - const found: Section[] = [] - let group = "" - let current: Section | undefined - for (const { line, insideCodeBlock } of markdownLines(markdown.split("\n"))) { - const heading = insideCodeBlock ? undefined : sectionHeading.exec(line)?.groups - if (heading?.title !== undefined) { - if (heading.level === "##") group = heading.title - current = - heading.level === "#" ? undefined : { heading: heading.title, group, lines: [] } - if (current) found.push(current) - } else if (insideCodeBlock || line !== backLink) { - current?.lines.push(line) - } - } - return found -} diff --git a/website/src/site-content/siteLinkTargets.ts b/website/src/site-content/siteLinkTargets.ts new file mode 100644 index 0000000..2bd206c --- /dev/null +++ b/website/src/site-content/siteLinkTargets.ts @@ -0,0 +1,11 @@ +import { headingAnchor } from "./internalLinks.ts" +import { publishedSite } from "./publishedSite.ts" + +const { base } = publishedSite + +export const routeOf = (id: string) => (id === "index" ? `${base}/` : `${base}/${id}/`) + +export const pageHeadingAnchors = (body: string) => + [...body.matchAll(/^#{1,6} (?<heading>.+)$/gmu)].map(({ groups }) => + headingAnchor(groups?.heading ?? ""), + ) diff --git a/website/src/site-content/sitePages.test.ts b/website/src/site-content/sitePages.test.ts index d3ae615..8680f42 100644 --- a/website/src/site-content/sitePages.test.ts +++ b/website/src/site-content/sitePages.test.ts @@ -1,160 +1,79 @@ import assert from "node:assert/strict" import { test } from "node:test" -import { - group, - pagesOf, - readmeMarkdown, - ruleSection, - rulesMarkdown, -} from "./sourceMarkdownBuilders.ts" - -const pageById = (sources: Parameters<typeof pagesOf>[0], id: string) => - pagesOf(sources).find((page) => page.id === id) - -test("a link to a rule section points to the page of that rule", () => { - const markdown = rulesMarkdown( - group( - "Error channel", - ruleSection("no-effect-promise"), - ruleSection("try-object-form", { - intent: "**Intent**: like [`no-effect-promise`](#no-effect-promise).", - }), - ), - ) - - const page = pageById({ rulesMd: markdown }, "rules/try-object-form") - - assert.ok(page?.body.includes("like [`no-effect-promise`](/site/rules/no-effect-promise/).")) -}) - -test("a link to Shared settings or Common limits points to its page", () => { - const markdown = rulesMarkdown( - "## Common limits\n\n- **Syntax only**.\n", - "## Shared settings\n\n- **`testFiles`**.\n", - group( - "Error channel", - ruleSection("no-effect-promise", { - options: "**Options**:\n\n- `testFiles`: [shared setting](#shared-settings).", - exemptions: "**Exemptions and blind spots**: see [limits](#common-limits).", - }), - ), - ) - - const page = pageById({ rulesMd: markdown }, "rules/no-effect-promise") - - assert.ok(page?.body.includes("[shared setting](/site/shared-settings/)")) - assert.ok(page?.body.includes("[limits](/site/common-limits/)")) -}) - -test("a link to a group points to the first rule of that group", () => { - const markdown = rulesMarkdown( - "## Shared settings\n\nUsed by [Error channel](#error-channel).\n", - group("Error channel", ruleSection("no-effect-promise"), ruleSection("try-object-form")), - ) - - const page = pageById({ rulesMd: markdown }, "shared-settings") - - assert.ok(page?.body.includes("[Error channel](/site/rules/no-effect-promise/)")) -}) - -test("a link to the rules index points to the rules overview", () => { - const markdown = rulesMarkdown( - "## Shared settings\n\nListed in the [rules index](#rules-index).\n", - group("Error channel", ruleSection("no-effect-promise")), - ) +import { type GuideFile } from "./sitePages.ts" +import { guideFile, pagesOf, ruleFile, rulesIndexFile } from "./sourceMarkdownBuilders.ts" - const page = pageById({ rulesMd: markdown }, "shared-settings") +const pageById = (userGuide: GuideFile[], id: string) => + pagesOf(userGuide).find((page) => page.id === id) - assert.ok(page?.body.includes("[rules index](/site/rules-overview/)")) -}) +test("a link from a rule file to a sibling rule file points to the page of that rule", () => { + const userGuide = [ + rulesIndexFile("no-effect-promise", "try-object-form"), + ruleFile("no-effect-promise", { + fields: { intent: "**Intent**: lift with [`Effect.tryPromise`](try-object-form.md)." }, + }), + ruleFile("try-object-form"), + ] -test("a RULES.md link to a section that has no site page fails, naming the link and the rule", () => { - const markdown = rulesMarkdown( - group( - "Error channel", - ruleSection("no-effect-promise", { why: "**Why**: see [gone](#removed-rule)." }), - ), - ) + const page = pageById(userGuide, "rules/no-effect-promise") - assert.throws(() => pagesOf({ rulesMd: markdown }), { - message: - "RULES.md, rule `no-effect-promise`: link `#removed-rule` resolves to no site page", - }) -}) - -test("the landing page shows the package scope above its name, the first paragraph as tagline, and links to installation and the rules overview", () => { - const readmeMd = [ - "# @owner/the-plugin\n\nAn oxlint plugin.\n\nIt complements [tsgo](#alongside-effecttsgo).\n", - "## Installation\n\n```bash\npnpm add -D the-plugin\n```\n", - "## Configuration\n\n### Alongside `@effect/tsgo`\n\nBoth.\n", - ].join("\n") - - const page = pageById({ readmeMd }, "index") - - assert.deepEqual(page, { - kind: "landing", - id: "index", - title: "@owner/the-plugin", - scope: "@owner/", - name: "the-plugin", - tagline: "An oxlint plugin.", - body: "It complements [tsgo](/site/configuration/#alongside-effecttsgo).\n", - actions: [ - { text: "Installation", link: "/site/installation/" }, - { text: "Rules overview", link: "/site/rules-overview/" }, - ], - }) + assert.ok(page?.body.includes("[`Effect.tryPromise`](/site/rules/try-object-form/).")) }) -test("a link to a README section points to its page, a link to a subsection to its heading there", () => { - const readmeMd = readmeMarkdown( - "## Installation\n\nThen [configure](#configuration), [with tsgo](#alongside-effecttsgo).\n", - "## Configuration\n\nExtend.\n\n### Alongside `@effect/tsgo`\n\nBoth.\n", - ) +test("a link from a rule file to a guide file points to its page", () => { + const userGuide = [ + rulesIndexFile("no-effect-promise"), + ruleFile("no-effect-promise", { + fields: { + options: "**Options**:\n\n- `testFiles`: [shared setting](../shared-settings.md).", + }, + }), + guideFile("shared-settings.md"), + ] - const page = pageById({ readmeMd }, "installation") + const page = pageById(userGuide, "rules/no-effect-promise") - assert.equal( - page?.body, - "Then [configure](/site/configuration/), [with tsgo](/site/configuration/#alongside-effecttsgo).\n", - ) + assert.ok(page?.body.includes("[shared setting](/site/shared-settings/)")) }) -test("a link to the Rules section points to the rules overview", () => { - const readmeMd = readmeMarkdown( - "## Rules\n\n| Topic | Rules |\n\n### Absorbed from anti-slop\n\nSome rules.\n", - "## Versioning\n\nSee the [overview](#rules) and [provenance](#absorbed-from-anti-slop).\n", - ) +test("a link from a guide file to a rule file points to the page of that rule", () => { + const userGuide = [ + rulesIndexFile("no-effect-promise"), + ruleFile("no-effect-promise"), + guideFile("common-limits.md", {}, "See [this](rules/no-effect-promise.md).\n"), + ] - const pages = pagesOf({ readmeMd }) + const page = pageById(userGuide, "common-limits") - assert.equal( - pages.find(({ id }) => id === "versioning")?.body, - "See the [overview](/site/rules-overview/) and [provenance](/site/rules-overview/#absorbed-from-anti-slop).\n", - ) + assert.equal(page?.body, "See [this](/site/rules/no-effect-promise/).\n") }) -test("a link from the README to RULES.md points to the rules overview, a link to a rule in it to the rule page", () => { - const readmeMd = readmeMarkdown( - "## Versioning\n\nIn [`RULES.md`](RULES.md), such as [this](RULES.md#no-effect-promise).\n", - ) +test("a link from a rule file to a repository file with no page points to that file on the main branch", () => { + const userGuide = [ + rulesIndexFile("anti-slop-prefer-effect-match"), + ruleFile("anti-slop-prefer-effect-match", { + fields: { why: "**Why**: see the [license](../../../LICENSE.anti-slop)." }, + }), + ] - const page = pageById({ readmeMd }, "versioning") + const page = pageById(userGuide, "rules/anti-slop-prefer-effect-match") - assert.equal( - page?.body, - "In [`RULES.md`](/site/rules-overview/), such as [this](/site/rules/no-effect-promise/).\n", + assert.ok( + page?.body.includes( + "[license](https://github.com/owner/the-plugin/blob/main/LICENSE.anti-slop)", + ), ) }) -test("a link to the Development section fails, as it has no site page", () => { - const readmeMd = readmeMarkdown( - "## Versioning\n\nSee [releasing](#development).\n", - "## Development\n\n- `pnpm release`.\n", - ) +test("a link from a rule file to a missing rule file fails the build, naming the file and the link", () => { + const userGuide = [ + rulesIndexFile("no-effect-promise"), + ruleFile("no-effect-promise", { fields: { why: "**Why**: see [gone](removed-rule.md)." } }), + ] - assert.throws(() => pagesOf({ readmeMd }), { - message: "README.md, section `Versioning`: link `#development` resolves to no site page", + assert.throws(() => pagesOf(userGuide), { + message: + "docs/user-guide/rules/no-effect-promise.md: link `removed-rule.md` resolves to no site page", }) }) diff --git a/website/src/site-content/sitePages.ts b/website/src/site-content/sitePages.ts index d79f236..1bdd71c 100644 --- a/website/src/site-content/sitePages.ts +++ b/website/src/site-content/sitePages.ts @@ -1,10 +1,8 @@ -import { type LinkRoutes, resolveLink, rewriteInternalLinks } from "./internalLinks.ts" -import { readmeMdSource } from "./readmeMdSource.ts" -import { rulesMdSource } from "./rulesMdSource.ts" +import { resolveLink, rewriteInternalLinks } from "./internalLinks.ts" +import { userGuideSource } from "./userGuideSource.ts" export type SitePage = | { kind: "rule"; id: string; title: string; group: string; body: string } - | { kind: "reference"; id: string; title: string; body: string } | { kind: "guide"; id: string; title: string; body: string } | { kind: "landing" @@ -19,19 +17,19 @@ export type SitePage = type LandingAction = { text: string; link: string } -export type SourcePage = { page: SitePage; file: string; location: string } +export type SourcePage = { page: SitePage; file: string } -export type SiteSources = { rulesMd: string; readmeMd: string } +// `path` is relative to the user-guide directory +export type GuideFile = { path: string; content: string } + +export type SiteSources = { userGuide: GuideFile[] } export type SiteOptions = { base: string; repositoryUrl: string } -export const sitePages = ({ rulesMd, readmeMd }: SiteSources, options: SiteOptions) => { - const sources = [readmeMdSource(readmeMd), rulesMdSource(rulesMd)] - const routes: LinkRoutes = new Map(sources.flatMap((source) => [...source.routes])) - return sources - .flatMap(({ sourcePages }) => sourcePages) - .map(({ page, file, location }): SitePage => { - const source = { ...options, file, location, routes } +export const sitePages = ({ userGuide }: SiteSources, options: SiteOptions) => { + const { sourcePages, routes } = userGuideSource(userGuide) + return sourcePages.map(({ page, file }): SitePage => { + const source = { ...options, file, routes } const body = rewriteInternalLinks(page.body, source) if (page.kind !== "landing") return { ...page, body } const actions = page.actions.map(({ text, link }) => ({ diff --git a/website/src/site-content/sourceMarkdownBuilders.ts b/website/src/site-content/sourceMarkdownBuilders.ts index 1b3b567..804c887 100644 --- a/website/src/site-content/sourceMarkdownBuilders.ts +++ b/website/src/site-content/sourceMarkdownBuilders.ts @@ -1,5 +1,4 @@ -import { backLink } from "./rulesMdSource.ts" -import { type SiteOptions, type SiteSources, sitePages } from "./sitePages.ts" +import { type GuideFile, type SiteOptions, sitePages } from "./sitePages.ts" type RuleFields = { intent: string @@ -13,7 +12,7 @@ type RuleFields = { export const wellFormedFields: RuleFields = { intent: "**Intent**: do the right thing.", - example: "```ts\n// no\nwrong()\n\n// yes\nright()\n```", + example: "```ts\n// ❌ no\nwrong()\n\n// ✅ yes\nright()\n```", trigger: "**Trigger**: a call to `wrong`.", exemptions: "**Exemptions and blind spots**: aliases slip through.", why: "**Why**: wrong things cost.", @@ -26,31 +25,43 @@ export const testSite: SiteOptions = { repositoryUrl: "https://github.com/owner/the-plugin", } -export const ruleSection = ( - name: string, - fields: Partial<Record<keyof RuleFields, string | null>> = {}, -) => - [`### \`${name}\``, backLink, ...Object.values({ ...wellFormedFields, ...fields })] +export const frontmatter = (fields: Record<string, string | number>) => + ["---", ...Object.entries(fields).map(([key, value]) => `${key}: ${value}`), "---", ""].join("\n") + +export const guideFile = ( + path: string, + fields: Record<string, string | number> = {}, + body = "Some text.\n", +): GuideFile => ({ path, content: `${frontmatter({ title: "A page", ...fields })}\n${body}` }) + +export const ruleBody = (fields: Partial<Record<keyof RuleFields, string | null>> = {}) => + Object.values({ ...wellFormedFields, ...fields }) .filter((block) => block !== null) .join("\n\n") + "\n" -export const rulesMarkdown = (...groups: string[]) => - ["# Rules\n", "## Rules index\n\n| Group | Rule |\n| --- | --- |\n", ...groups].join("\n") - -export const group = (title: string, ...sections: string[]) => - [`## ${title}\n`, ...sections].join("\n") - -// The landing page links to Installation, so a README always has one -export const readmeMarkdown = (...sections: string[]) => - [ - "# the-plugin\n\nA plugin.\n", - ...sections, - ...(sections.some((section) => section.startsWith("## Installation\n")) - ? [] - : ["## Installation\n\nInstall it.\n"]), - ].join("\n") - -export const pagesOf = ({ - rulesMd = rulesMarkdown(group("Error channel", ruleSection("no-effect-promise"))), - readmeMd = readmeMarkdown(), -}: Partial<SiteSources>) => sitePages({ rulesMd, readmeMd }, testSite) +export const ruleFile = ( + name: string, + { + group = "Error channel", + fields = {}, + }: { group?: string; fields?: Parameters<typeof ruleBody>[0] } = {}, +): GuideFile => ({ + path: `rules/${name}.md`, + content: `${frontmatter({ title: name, group })}\n${ruleBody(fields)}`, +}) + +// The rules index orders the rule pages by the order of its links +export const rulesIndexFile = (...rules: string[]) => + guideFile( + "rules.md", + { title: "Rules overview" }, + `${rules.map((rule) => `- [\`${rule}\`](rules/${rule}.md)`).join("\n")}\n`, + ) + +export const pagesOf = (userGuide: GuideFile[]) => sitePages({ userGuide }, testSite) + +export const guidePagesOf = (userGuide: GuideFile[]) => + pagesOf(userGuide).filter(({ kind }) => kind === "guide" || kind === "landing") + +export const rulePagesOf = (userGuide: GuideFile[]) => + pagesOf(userGuide).filter((page) => page.kind === "rule") diff --git a/website/src/site-content/userGuideAlignment.test.ts b/website/src/site-content/userGuideAlignment.test.ts new file mode 100644 index 0000000..5e19d33 --- /dev/null +++ b/website/src/site-content/userGuideAlignment.test.ts @@ -0,0 +1,133 @@ +import assert from "node:assert/strict" +import { access } from "node:fs/promises" +import { test } from "node:test" + +import { markdownLinkHrefs } from "./internalLinks.ts" +import { publishedSite } from "./publishedSite.ts" +import { readSiteSources } from "./readSiteSources.ts" +import { repositoryRoot } from "./realRepository.ts" +import { pageHeadingAnchors, routeOf } from "./siteLinkTargets.ts" +import { sitePages } from "./sitePages.ts" + +const sources = await readSiteSources(new URL("website/", repositoryRoot)) +const pages = sitePages(sources, publishedSite) +const { base, repositoryUrl } = publishedSite + +const frontmatterTitle = (content: string) => + /^title: "?(?<title>.+?)"?$/mu.exec(content)?.groups?.title + +// The guide index is the landing page and the rules index the rules overview, stated apart from +// how the site derives them +const expectedPageIds = new Map([ + ["README.md", "index"], + ["rules.md", "rules-overview"], +]) + +const pageOf = (path: string) => + pages.find(({ id }) => id === (expectedPageIds.get(path) ?? path.replace(/\.md$/u, ""))) + +test("the real user guide has guide files", () => { + assert.ok(sources.userGuide.length > 0) +}) + +const isRuleFile = (path: string) => path.startsWith("rules/") + +for (const { path, content } of sources.userGuide.filter( + ({ path }) => path !== "README.md" && !isRuleFile(path), +)) { + test(`the real guide file ${path} is a guide page with its frontmatter title`, () => { + const page = pageOf(path) + + assert.equal(page?.kind, "guide") + assert.equal(page?.title, frontmatterTitle(content)) + }) +} + +test("every real rule file is a rule page named after its file", () => { + const ruleFileNames = sources.userGuide + .filter(({ path }) => isRuleFile(path)) + .map(({ path }) => path.replace(/^rules\/(?<name>.+)\.md$/u, "$<name>")) + .toSorted() + + const rulePageTitles = pages + .filter(({ kind }) => kind === "rule") + .map(({ title }) => title) + .toSorted() + + assert.ok(ruleFileNames.length > 0) + assert.deepEqual(rulePageTitles, ruleFileNames) +}) + +const rulesIndexRow = /^\| (?<topic>[^|]+?) +\| (?<rules>.+) \|$/gmu +const ruleLink = /\]\(rules\/(?<rule>[a-z-]+)\.md\)/gu + +// The topic table comes first in the rules index, before any other table that links rules +const rulesIndexTopics = () => { + const rulesIndex = sources.userGuide.find(({ path }) => path === "rules.md")?.content ?? "" + const topicTable = rulesIndex.split("\n\n").find((block) => block.startsWith("| Topic")) + return [...(topicTable ?? "").matchAll(rulesIndexRow)].flatMap(({ groups }) => + [...(groups?.rules ?? "").matchAll(ruleLink)].map((link) => ({ + id: `rules/${link.groups?.rule}`, + group: groups?.topic ?? "", + })), + ) +} + +test("real rule pages sit in the group of their topic in the rules index, in its order", () => { + const rulePages = pages.flatMap((page) => + page.kind === "rule" ? [{ id: page.id, group: page.group }] : [], + ) + + assert.deepEqual(rulePages, rulesIndexTopics()) +}) + +test("the real guide index is the landing page, with the package scope above its name and its first paragraph as tagline", () => { + const landing = pageOf("README.md") + + assert.ok(landing?.kind === "landing") + assert.equal(landing.scope, "@doubleloop-io/") + assert.equal(landing.name, "oxlint-plugin-effect") + assert.equal(landing.tagline, "An oxlint plugin that enforces a catalog of patterns for Effect 4 code.") + assert.deepEqual( + landing.actions.map(({ text }) => text), + ["Installation", "Rules overview"], + ) +}) + +// Rule pages are reached through the rules index, which the build already requires to link them +test("the real guide index links to every guide page", () => { + const indexHrefs = markdownLinkHrefs(pageOf("README.md")?.body ?? "") + const unlinked = sources.userGuide + .filter(({ path }) => path !== "README.md" && !isRuleFile(path)) + .map(({ path }) => pageOf(path)?.id ?? path) + .filter((id) => !indexHrefs.includes(routeOf(id))) + + assert.deepEqual(unlinked, []) +}) + +const guideHrefs = () => + sources.userGuide.flatMap(({ path }) => { + const page = pageOf(path) + const actionLinks = page?.kind === "landing" ? page.actions.map(({ link }) => link) : [] + return [...markdownLinkHrefs(page?.body ?? ""), ...actionLinks] + }) + +test("every internal link of the real user guide points to an existing site page and heading", () => { + for (const href of guideHrefs().filter((link) => link.startsWith(`${base}/`))) { + const [route, anchor] = href.split("#") + const target = pages.find(({ id }) => routeOf(id) === route) + assert.ok(target, `${href} is not a site page`) + if (anchor !== undefined) { + assert.ok(pageHeadingAnchors(target.body).includes(anchor), `${href} has no heading`) + } + } +}) + +test("every link of the real user guide to a repository file points to a file that exists", async () => { + const fileHrefs = guideHrefs().filter((href) => href.startsWith(`${repositoryUrl}/blob/main/`)) + + for (const href of fileHrefs) { + const file = new URL(href.replace(`${repositoryUrl}/blob/main/`, ""), repositoryRoot) + await assert.doesNotReject(access(file), `${href} is not a repository file`) + } +}) diff --git a/website/src/site-content/userGuidePages.test.ts b/website/src/site-content/userGuidePages.test.ts new file mode 100644 index 0000000..00195fc --- /dev/null +++ b/website/src/site-content/userGuidePages.test.ts @@ -0,0 +1,138 @@ +import assert from "node:assert/strict" +import { test } from "node:test" + +import { frontmatter, guideFile, guidePagesOf } from "./sourceMarkdownBuilders.ts" + +test("a guide file is a guide page with the title of its frontmatter, named after its path", () => { + const userGuide = [guideFile("versioning.md", { title: "Versioning" }, "Versions are `0.x`.\n")] + + const pages = guidePagesOf(userGuide) + + assert.deepEqual(pages, [ + { kind: "guide", id: "versioning", title: "Versioning", body: "Versions are `0.x`.\n" }, + ]) +}) + +test("the guide index is the landing page: the package scope above its name, the first paragraph as tagline, and actions to installation and the rules overview", () => { + const userGuide = [ + guideFile( + "README.md", + { title: '"@owner/the-plugin"' }, + "An oxlint plugin.\n\nStart from [configuration](configuration.md).\n", + ), + guideFile("installation.md"), + guideFile("configuration.md"), + guideFile("rules.md"), + ] + + const landing = guidePagesOf(userGuide).find(({ kind }) => kind === "landing") + + assert.deepEqual(landing, { + kind: "landing", + id: "index", + title: "@owner/the-plugin", + scope: "@owner/", + name: "the-plugin", + tagline: "An oxlint plugin.", + body: "Start from [configuration](/site/configuration/).\n", + actions: [ + { text: "Installation", link: "/site/installation/" }, + { text: "Rules overview", link: "/site/rules-overview/" }, + ], + }) +}) + +test("the rules index is the rules overview page, apart from the route of the rule pages", () => { + const userGuide = [guideFile("rules.md", { title: "Rules overview" }, "| Topic | Rules |\n")] + + const pages = guidePagesOf(userGuide) + + assert.deepEqual(pages, [ + { kind: "guide", id: "rules-overview", title: "Rules overview", body: "| Topic | Rules |\n" }, + ]) +}) + +test("guide pages follow the order of their frontmatter, then their path, whatever the file order", () => { + const userGuide = [ + guideFile("zebra.md"), + guideFile("troubleshooting.md", { order: 2 }), + guideFile("alpha.md"), + guideFile("versioning.md", { order: 1 }), + ] + + const ids = guidePagesOf(userGuide).map(({ id }) => id) + + assert.deepEqual(ids, ["versioning", "troubleshooting", "alpha", "zebra"]) +}) + +test("a relative link to a guide file points to its page, one with an anchor to its heading there", () => { + const userGuide = [ + guideFile("versioning.md", {}, "See [settings](configuration.md), [rc](configuration.md#release-candidates), [here](#policy).\n\n## Policy\n"), + guideFile("configuration.md", {}, "## Release candidates\n\nText.\n"), + ] + + const page = guidePagesOf(userGuide).find(({ id }) => id === "versioning") + + assert.equal( + page?.body, + "See [settings](/site/configuration/), [rc](/site/configuration/#release-candidates), [here](/site/versioning/#policy).\n\n## Policy\n", + ) +}) + +for (const { condition, href } of [ + { condition: "a missing guide file", href: "removed.md" }, + { condition: "a missing heading", href: "configuration.md#removed-heading" }, +]) { + test(`a link to ${condition} fails the build, naming the file and the link`, () => { + const userGuide = [ + guideFile("versioning.md", {}, `See [this](${href}).\n`), + guideFile("configuration.md", {}, "## Settings\n"), + ] + + assert.throws(() => guidePagesOf(userGuide), { + message: `docs/user-guide/versioning.md: link \`${href}\` resolves to no site page`, + }) + }) +} + +test("a relative link to a repository file with no page points to that file on the main branch", () => { + const userGuide = [guideFile("versioning.md", {}, "See the [license](../../LICENSE).\n")] + + const page = guidePagesOf(userGuide).find(({ id }) => id === "versioning") + + assert.equal(page?.body, "See the [license](https://github.com/owner/the-plugin/blob/main/LICENSE).\n") +}) + +const invalidFrontmatter = [ + { condition: "no frontmatter", content: "Versions are `0.x`.\n", problem: "no frontmatter" }, + { + condition: "a frontmatter without title", + content: `${frontmatter({ order: 1 })}\nText.\n`, + problem: "frontmatter has no `title`", + }, + { + condition: "an order that is not an integer", + content: `${frontmatter({ title: "Versioning", order: "first" })}\nText.\n`, + problem: "frontmatter `order` is not an integer", + }, + { + condition: "a frontmatter line that is not a field", + content: "---\ntitle: Versioning\njust text\n---\n\nText.\n", + problem: "frontmatter line `just text` is not `field: value`", + }, + { + condition: "an unknown field", + content: `${frontmatter({ title: "Versioning", sidebar: "hidden" })}\nText.\n`, + problem: "frontmatter has unknown field `sidebar`", + }, +] + +for (const { condition, content, problem } of invalidFrontmatter) { + test(`a guide file with ${condition} fails the build, naming the file`, () => { + const userGuide = [{ path: "versioning.md", content }] + + assert.throws(() => guidePagesOf(userGuide), { + message: `docs/user-guide/versioning.md: ${problem}`, + }) + }) +} diff --git a/website/src/site-content/userGuideSource.ts b/website/src/site-content/userGuideSource.ts new file mode 100644 index 0000000..be53399 --- /dev/null +++ b/website/src/site-content/userGuideSource.ts @@ -0,0 +1,170 @@ +import { headingAnchor, markdownLinkHrefs } from "./internalLinks.ts" +import { markdownLines } from "./markdownLines.ts" +import { ruleTemplateProblem } from "./ruleTemplate.ts" +import type { GuideFile, SitePage, SourcePage } from "./sitePages.ts" + +export const userGuideDirectory = "docs/user-guide" + +const guideIndexPath = "README.md" + +const rulesIndexPath = "rules.md" + +export const rulesOverviewId = "rules-overview" + +// `rules/` is the parent route of the rule pages, so the rules index has a route of its own +const pageIds = new Map([ + [guideIndexPath, "index"], + [rulesIndexPath, rulesOverviewId], +]) + +const landingActions = [ + { text: "Installation", link: "installation.md" }, + { text: "Rules overview", link: rulesIndexPath }, +] + +// Whether a file is a rule is decided once, from its path, when it is parsed +type ParsedGuideFile = { path: string; title: string; body: string } & ( + | { kind: "rule"; group: string } + | { kind: "page"; order: number } +) + +const frontmatterBlock = /^---\n(?<fields>(?:.*\n)*?)---\n/u + +export const userGuideSource = (files: GuideFile[]) => { + const parsed = files.map(parseGuideFile) + const pages = parsed.filter((file) => file.kind === "page").toSorted(byOrderThenPath) + const ordered = [...pages, ...inRulesIndexOrder(parsed)] + return { sourcePages: ordered.map(sourcePage), routes: new Map(ordered.flatMap(linkRoutes)) } +} + +// The rules index sits next to `rules/`, so its links to rule files are their paths +const inRulesIndexOrder = (files: ParsedGuideFile[]) => { + const rulesIndex = files.find(({ path }) => path === rulesIndexPath) + const linkedPaths = markdownLinkHrefs(rulesIndex?.body ?? "") + const position = ({ path }: ParsedGuideFile) => { + const index = linkedPaths.indexOf(path) + if (index === -1) { + throw guideFileError( + path, + `not linked from the rules index, ${userGuideDirectory}/${rulesIndexPath}`, + ) + } + return index + } + return files + .filter((file) => file.kind === "rule") + .map((file) => ({ file, position: position(file) })) + .toSorted((left, right) => left.position - right.position) + .map(({ file }) => file) +} + +const markdownHeading = /^#{1,6} (?<heading>.+)$/u + +const linkRoutes = ({ path, body }: ParsedGuideFile) => { + const file = `${userGuideDirectory}/${path}` + const id = pageId(path) + const route = id === "index" ? "" : `${id}/` + const anchors = markdownLines(body.split("\n")).flatMap(({ line, insideCodeBlock }) => { + const heading = insideCodeBlock ? undefined : markdownHeading.exec(line)?.groups?.heading + return heading === undefined ? [] : [headingAnchor(heading)] + }) + return [ + [file, route] as const, + ...anchors.map((anchor) => [`${file}#${anchor}`, `${route}#${anchor}`] as const), + ] +} + +const pageId = (path: string) => pageIds.get(path) ?? path.replace(/\.md$/u, "") + +type OrderedFile = { path: string; order: number } + +const byOrderThenPath = (left: OrderedFile, right: OrderedFile) => + left.order - right.order || left.path.localeCompare(right.path) + +const ruleDirectory = "rules/" + +const isRuleFile = (path: string) => path.startsWith(ruleDirectory) + +const guideFields = new Set(["title", "order"]) +const ruleFields = new Set(["title", "group"]) + +const frontmatterField = /^(?<field>[\w-]+): *(?<value>.*)$/u + +// YAML needs quotes around a value that starts with a reserved character such as `@` +const quotedValue = /^"(?<text>.*)"$/u + +const integer = /^-?\d+$/u + +const parseGuideFile = ({ path, content }: GuideFile): ParsedGuideFile => { + const block = frontmatterBlock.exec(content) + if (block === null) throw guideFileError(path, "no frontmatter") + const fields = new Map( + (block.groups?.fields ?? "") + .split("\n") + .filter((line) => line.trim() !== "") + .map((line) => { + const { field, value = "" } = frontmatterField.exec(line)?.groups ?? {} + if (field === undefined) { + throw guideFileError(path, `frontmatter line \`${line}\` is not \`field: value\``) + } + if (!(isRuleFile(path) ? ruleFields : guideFields).has(field)) { + throw guideFileError(path, `frontmatter has unknown field \`${field}\``) + } + const trimmed = value.trim() + return [field, quotedValue.exec(trimmed)?.groups?.text ?? trimmed] as const + }), + ) + const title = fields.get("title") + if (title === undefined || title === "") throw guideFileError(path, "frontmatter has no `title`") + const order = fields.get("order") + if (order !== undefined && !integer.test(order)) { + throw guideFileError(path, "frontmatter `order` is not an integer") + } + const body = `${content.slice(block[0].length).trim()}\n` + if (isRuleFile(path)) { + const group = fields.get("group") + if (group === undefined || group === "") throw guideFileError(path, "frontmatter has no `group`") + return { kind: "rule", path, title, group, body } + } + // A page without an order goes after the ordered ones + const position = order === undefined ? Number.POSITIVE_INFINITY : Number(order) + return { kind: "page", path, title, order: position, body } +} + +const guideFileError = (path: string, problem: string) => + new Error(`${userGuideDirectory}/${path}: ${problem}`) + +const sourcePage = (file: ParsedGuideFile): SourcePage => ({ + page: sitePage(file), + file: `${userGuideDirectory}/${file.path}`, +}) + +const sitePage = (file: ParsedGuideFile): SitePage => { + const { path, title, body } = file + if (file.kind === "rule") { + const problem = ruleTemplateProblem(body) + if (problem !== undefined) throw guideFileError(path, problem) + return { kind: "rule", id: pageId(path), title, group: file.group, body } + } + if (path === guideIndexPath) return landingPage(title, body) + return { kind: "guide", id: pageId(path), title, body } +} + +const packageName = /^(?<scope>@[^/]+\/)?(?<name>.+)$/u + +// The title is the package name, split so the scope can sit above the name; +// the first paragraph is the tagline under it, so the body starts after it +const landingPage = (title: string, body: string): SitePage => { + const { scope, name = title } = packageName.exec(title)?.groups ?? {} + const [tagline = "", ...rest] = body.split("\n\n") + return { + kind: "landing", + id: "index", + title, + scope, + name, + tagline: tagline.trim(), + body: rest.length === 0 ? "" : `${rest.join("\n\n").trim()}\n`, + actions: landingActions, + } +}