react-doctor icon indicating copy to clipboard operation
react-doctor copied to clipboard

feat: library-aware React 19 rules + test-file scoping + build-entry dead-code + js-set-map-lookups string fix

Open aidenybai opened this issue 6 months ago • 11 comments

Motivation

User feedback from a library author who scanned @pierre/diffs (rolled up across multiple rounds):

Obvi what i talked about in the tweet with like this being a library and trying to increase compatibility, we use forwardRef for that reason. But in a react 19 app obvi you shouldn't be using that, so i get the decision.

we have 2 files that are exported from our build, but not imported anywhere, that get listed as dead code

I kinda wonder if test or tests directory and/or files should be ignored?

also getting penalized for using indexOf on a string … also getting dinged for using includes on a string (Element.textContent)

This PR addresses all four — three new project-driven defaults plus a targeted false-positive fix on js-set-map-lookups.

Four fixes

1. Library-aware React 19 deprecation rules

When a package declares react as a peerDependency with a range that admits any React major below 19 (e.g. ^17 || ^18 || ^19, >=17, ^16.8 || ^17 || ^18 || ^19, plain *, or a pnpm catalog: reference resolving to one of the above), three rules now skip:

  • react-doctor/no-react19-deprecated-apis (forwardRef, useContext)
  • react-doctor/no-default-props
  • react-doctor/no-react-dom-deprecated-apis

The library MUST keep these APIs to honor its peer contract. prefer-use-effect-event and other prefer-newer-api rules keep firing — library context is about not breaking peer compat, not about hiding generally useful API recommendations.

2. Test-file rule scoping

Tests intentionally exercise patterns that would be wrong in production: array-index keys in fixture rows, oversize fixture components, forwardRef/defaultProps/flushSync assertions, design-system spot checks, micro-perf patterns in fixture loops, etc. Files matching .test.* / .spec.* / .stories.* or anything under __tests__ / tests / test / __mocks__ / cypress / e2e / playwright now skip a curated set of "noise-in-fixtures" rules. Correctness rules (rules-of-hooks, effect-needs-cleanup, the react-hooks-js/* compiler rules, alt-text, role-has-required-aria-props, …) keep firing — a buggy test is still a bug.

Opt out via suppressNoiseRulesInTestFiles: false.

3. Build-entry dead-code suppression

Knip's files rule flags source files that no other source file imports — but library entry points (CLI scripts, web/service workers, additional bundle entries) are imported by the BUILD process, not by other source files. We now suppress knip/files when the source has a matching artifact under any of the standard build dirs (dist / build / lib / out / esm / cjs) with a .js / .mjs / .cjs extension.

Conservative in the right direction: false negatives (real dead code with a coincidental dist artifact) are vanishingly rare; false positives (real entry flagged as dead) were the actual user-facing pain. Requires the project to have been built — pre-build, every entry is still flagged.

Opt out via suppressDeadCodeForBuildEntries: false.

4. js-set-map-lookups skips string receivers

The rule's premise — "convert to a Set for O(1) lookups" — only applies to arrays. Strings have no Set equivalent for substring search, so flagging string.indexOf() / string.includes() is wrong advice. Two reported false positives:

  • contents.indexOf('\n', cursor) where contents: string
  • style?.textContent?.includes(expected) (DOM string property)

The rule now skips when the receiver is obviously a string. High-confidence detection signals (no type info available at the AST layer):

  • String / template literal receiver
  • String(...) cast
  • String-returning method call (.toString, .toLowerCase, .toUpperCase, .trim*, .pad*, .replace*, .substring, .substr, .normalize, .repeat, .charAt, .toFixed, …)
  • Member access ending in a known DOM/built-in string property (.textContent, .innerHTML, .outerHTML, .innerText, .nodeValue, .tagName, .className, URL parts, error properties, …)
  • Identifier with a name that overwhelmingly binds to a string (text, contents, html, json, url, path, line, needle, …) — ambiguous names like data, value, item deliberately omitted
  • ChainExpression wrapper transparently unwrapped so optional chaining (a?.textContent?.includes(x)) still detects the string property at the tail

Plus all JS micro-perf and async-perf rules (js-set-map-lookups, js-flatmap-filter, js-combine-iterations, async-await-in-loop, …) are now in the test-file disabled set — fixture loops over allow-lists shouldn't be held to production-perf standards.

The array-on-array case (the actual perf concern) still fires — verified by regression tests covering array.includes() and array.indexOf() on plain array variables.

Implementation notes

  • peerRangeSupportsLegacyReact() splits on semver's boolean separators (||, ,, whitespace), and a comparator votes "supports legacy" if it's a pure wildcard (*/x.x.x) or its first integer is in [1, 19). One vote flips the range. Reading only the first integer per comparator avoids false positives on minor/patch zeros (^19.0.0) and canary hex digits (0.0.0-canary-abc).
  • resolveReactPeerRange() reads the local package's peerDependencies.react, defensively guards against malformed entries (null / numbers), and resolves pnpm catalog: references through the catalog system. Named catalog references ("catalog:react18") forward the catalog name to resolveCatalogVersion so multi-grouped catalogs resolve to the correct group. Falls back to the monorepo root when the leaf package's directory has no pnpm-workspace.yaml (the common shape).
  • filterAutomaticSuppressions runs as a project-driven (no user-config required) filter pass in mergeAndFilterDiagnostics, ahead of the existing user-config / inline-suppression layers. Per-file results cached so an N-diagnostic file pays the test/build-entry checks once.
  • isLikelyStringReceiver lives next to the jsSetMapLookups rule — local to the one rule that needs it, no premature abstraction.
  • New boolean config fields wired into validateConfigTypes so JSON-typing mistakes are coerced + warned.

Tests

  • parse-react-peer-range.test.ts (7 cases): basic legacy-supporting ranges, 19+only ranges, wildcards, npm dist-tags, canary tags, double-counting 0 digits.
  • discoverProject cases: existing fixture, library with ^19.0.0 peer (no relaxation), app with no peer dep, wide ^16.8 || ^17 || ^18 || ^19 peer, * wildcard peer, pnpm catalog peer (resolves through monorepo root), named catalog peer (catalog:react18 correctly picks the react18 group over a sibling react19 group), malformed peer (react: null).
  • react-19-migration-rules.test.ts: each of the three deprecation rules in library mode + a "still flags prefer-use-effect-event in library mode" check.
  • is-test-file.test.ts (7 cases): .test.* / .spec.* suffixes, Storybook fixtures, test directories at any depth, Windows path normalization, false positives like contestants/, protest/, testing-utils.ts.
  • is-likely-build-entry.test.ts (9 cases): src/cli.ts ↔ dist/cli.js, the user-reported worker entries, every (build dir, ext) combo, top-level vs nested files, missing artifacts, Windows paths.
  • filter-automatic-suppressions.test.ts (11 cases): test-file scoping including opt-out, build-entry suppression including opt-out, fast-path when both disabled, JS micro-perf rules dropped in test files (regression).
  • js-set-map-lookups-string-fp.test.ts (9 cases): contents.indexOf('\n'), Element.textContent?.includes(), string literal / template literal / String(...) / .toLowerCase() chain receivers, optional-chained DOM property, plus two "still flags arrays" sanity cases for the array-on-array regression risk.

All 780 tests pass; lint, typecheck, format are clean.

Review feedback

  • Cursor Bugbot (commit ec42a02): caught a low-severity copy-paste duplicate — "tagName" listed twice in STRING_TYPED_PROPERTY_NAMES. Fixed in 49f0075.
  • Cursor Bugbot (commit e49eee0, post first merge): caught named catalog reference being dropped — resolveReactPeerRange was calling resolveCatalogVersion without forwarding the catalog NAME, so "catalog:react18" resolved against an arbitrary group rather than the requested react18 one. Fixed in 1336a0a plus a regression test that verifies the react18 group is picked over a sibling react19 group.
  • Two origin/main rebases handled cleanly: PR #201 (eslint-plugin-react-you-might-not-need-an-effect) and PR #202 (Tailwind version detection), both of which extended the same OxlintConfigOptions interface and call sites I added isLibraryTargetingLegacyReact to.
Open in Web Open in Cursor 

aidenybai avatar May 09 '26 06:05 aidenybai

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
react-doctor-website Ready Ready Preview, Comment May 10, 2026 3:04pm

vercel[bot] avatar May 09 '26 06:05 vercel[bot]

react review

aidenybai avatar May 09 '26 07:05 aidenybai

react review

aidenybai avatar May 09 '26 07:05 aidenybai

[!NOTE] No issues found

react-doctor[bot] avatar May 09 '26 12:05 react-doctor[bot]

react review

aidenybai avatar May 10 '26 03:05 aidenybai

react review

aidenybai avatar May 10 '26 03:05 aidenybai

react review

aidenybai avatar May 10 '26 04:05 aidenybai

react review

aidenybai avatar May 10 '26 04:05 aidenybai

react review

aidenybai avatar May 10 '26 04:05 aidenybai

react review

aidenybai avatar May 10 '26 05:05 aidenybai

react review

aidenybai avatar May 10 '26 05:05 aidenybai