├── .all-contributorsrc ├── .github ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── DEVELOPMENT.md ├── ISSUE_TEMPLATE.md ├── ISSUE_TEMPLATE │ ├── 01-bug.yml │ ├── 02-documentation.yml │ ├── 03-feature.yml │ └── 04-tooling.yml ├── PULL_REQUEST_TEMPLATE.md ├── SECURITY.md ├── actions │ └── prepare │ │ └── action.yml ├── renovate.json └── workflows │ ├── ci.yml │ ├── contributors.yml │ ├── octoguide.yml │ ├── post-release.yml │ ├── pr-review-requested.yml │ └── release.yml ├── .gitignore ├── .husky ├── .gitignore └── pre-commit ├── .markdownlint.json ├── .markdownlintignore ├── .nvmrc ├── .prettierignore ├── .prettierrc.json ├── .release-it.json ├── .vscode ├── extensions.json ├── launch.json ├── settings.json └── tasks.json ├── CHANGELOG.md ├── LICENSE.md ├── README.md ├── bin └── index.js ├── cspell.json ├── docs └── flint.png ├── eslint.config.js ├── knip.json ├── package.json ├── pnpm-lock.yaml ├── src ├── createRule.ts ├── index.ts ├── plugin.ts ├── plugins │ ├── createPlugin.test-d.ts │ ├── createPlugin.test.ts │ └── createPlugin.ts ├── rules │ ├── consecutiveNonNullAssertions.test.ts │ ├── consecutiveNonNullAssertions.ts │ ├── forInArrays.test.ts │ ├── forInArrays.ts │ ├── namespaceDeclarations.test.ts │ ├── namespaceDeclarations.ts │ └── utils │ │ ├── getConstrainedType.ts │ │ └── isTypeRecursive.ts ├── testing │ ├── RuleTester.ts │ ├── createProgramSourceFile.ts │ ├── createReportSnapshot.ts │ ├── normalizeRange.ts │ └── runTestCaseRule.ts └── types │ ├── configurations.ts │ ├── context.ts │ ├── nodes.ts │ ├── plugins.ts │ ├── reports.ts │ ├── rules.ts │ ├── shapes.ts │ └── testing.ts ├── tsconfig.json ├── tsup.config.ts └── vitest.config.ts /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "badgeTemplate": "\t\"👪\" src=\"https://img.shields.io/badge/%F0%9F%91%AA_all_contributors-<%= contributors.length %>-21bb42.svg\" />", 3 | "commitType": "docs", 4 | "contributors": [ 5 | { 6 | "avatar_url": "https://avatars.githubusercontent.com/u/3335181?v=4", 7 | "contributions": [ 8 | "code", 9 | "content", 10 | "doc", 11 | "ideas", 12 | "infra", 13 | "maintenance", 14 | "projectManagement", 15 | "tool" 16 | ], 17 | "login": "JoshuaKGoldberg", 18 | "name": "Josh Goldberg ✨", 19 | "profile": "http://www.joshuakgoldberg.com" 20 | } 21 | ], 22 | "contributorsPerLine": 7, 23 | "contributorsSortAlphabetically": true, 24 | "files": [ 25 | "README.md" 26 | ], 27 | "projectName": "flint", 28 | "projectOwner": "JoshuaKGoldberg", 29 | "repoType": "github", 30 | "commitConvention": "angular" 31 | } 32 | -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, caste, color, religion, or sexual 10 | identity and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | - Demonstrating empathy and kindness toward other people 21 | - Being respectful of differing opinions, viewpoints, and experiences 22 | - Giving and gracefully accepting constructive feedback 23 | - Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | - Focusing on what is best not just for us as individuals, but for the overall 26 | community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | - The use of sexualized language or imagery, and sexual attention or advances of 31 | any kind 32 | - Trolling, insulting or derogatory comments, and personal or political attacks 33 | - Public or private harassment 34 | - Publishing others' private information, such as a physical or email address, 35 | without their explicit permission 36 | - Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | git@joshuakgoldberg.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series of 86 | actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or permanent 93 | ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within the 113 | community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.1, available at 119 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 120 | 121 | Community Impact Guidelines were inspired by 122 | [Mozilla's code of conduct enforcement ladder][mozilla coc]. 123 | 124 | For answers to common questions about this code of conduct, see the FAQ at 125 | [https://www.contributor-covenant.org/faq][faq]. Translations are available at 126 | [https://www.contributor-covenant.org/translations][translations]. 127 | 128 | [homepage]: https://www.contributor-covenant.org 129 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 130 | [mozilla coc]: https://github.com/mozilla/diversity 131 | [faq]: https://www.contributor-covenant.org/faq 132 | [translations]: https://www.contributor-covenant.org/translations 133 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Thanks for your interest in contributing to `flint`! ❤️‍🔥 4 | 5 | > After this page, see [DEVELOPMENT.md](./DEVELOPMENT.md) for local development instructions. 6 | 7 | ## Code of Conduct 8 | 9 | This project contains a [Contributor Covenant code of conduct](./CODE_OF_CONDUCT.md) all contributors are expected to follow. 10 | 11 | ## Reporting Issues 12 | 13 | Please do [report an issue on the issue tracker](https://github.com/JoshuaKGoldberg/flint/issues/new/choose) if there's any bugfix, documentation improvement, or general enhancement you'd like to see in the repository! Please fully fill out all required fields in the most appropriate issue form. 14 | 15 | ## Sending Contributions 16 | 17 | Sending your own changes as contribution is always appreciated! 18 | There are two steps involved: 19 | 20 | 1. [Finding an Issue](#finding-an-issue) 21 | 2. [Sending a Pull Request](#sending-a-pull-request) 22 | 23 | ### Finding an Issue 24 | 25 | With the exception of very small typos, all changes to this repository generally need to correspond to an [unassigned open issue marked as `status: accepting prs` on the issue tracker](https://github.com/JoshuaKGoldberg/flint/issues?q=is%3Aissue+is%3Aopen+label%3A%22status%3A+accepting+prs%22+no%3Aassignee+). 26 | If this is your first time contributing, consider searching for [unassigned issues that also have the `good first issue` label](https://github.com/JoshuaKGoldberg/flint/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22+label%3A%22status%3A+accepting+prs%22+no%3Aassignee+). 27 | If the issue you'd like to fix isn't found on the issue, see [Reporting Issues](#reporting-issues) for filing your own (please do!). 28 | 29 | #### Issue Claiming 30 | 31 | We don't use any kind of issue claiming system. 32 | We've found in the past that they result in accidental ["licked cookie"](https://devblogs.microsoft.com/oldnewthing/20091201-00/?p=15843) situations where contributors claim an issue but run out of time or energy trying before sending a PR. 33 | 34 | If an unassigned issue has been marked as `status: accepting prs` and an open PR does not exist, feel free to send a PR. 35 | Please don't post comments asking for permission or stating you will work on an issue. 36 | 37 | ### Sending a Pull Request 38 | 39 | Once you've identified an open issue accepting PRs that doesn't yet have a PR sent, you're free to send a pull request. 40 | Be sure to fill out the pull request template's requested information -- otherwise your PR will likely be closed. 41 | 42 | PRs are also expected to have a title that adheres to [conventional commits](https://www.conventionalcommits.org/en/v1.0.0). 43 | Only PR titles need to be in that format, not individual commits. 44 | Don't worry if you get this wrong: you can always change the PR title after sending it. 45 | Check [previously merged PRs](https://github.com/JoshuaKGoldberg/flint/pulls?q=is%3Apr+is%3Amerged+-label%3Adependencies+) for reference. 46 | 47 | #### Draft PRs 48 | 49 | If you don't think your PR is ready for review, [set it as a draft](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#converting-a-pull-request-to-a-draft). 50 | Draft PRs won't be reviewed. 51 | 52 | #### Granular PRs 53 | 54 | Please keep pull requests single-purpose: in other words, don't attempt to solve multiple unrelated problems in one pull request. 55 | Send one PR per area of concern. 56 | Multi-purpose pull requests are harder and slower to review, block all changes from being merged until the whole pull request is reviewed, and are difficult to name well with semantic PR titles. 57 | 58 | #### Pull Request Reviews 59 | 60 | When a PR is not in draft, it's considered ready for review. 61 | Please don't manually `@` tag anybody to request review. 62 | A maintainer will look at it when they're next able to. 63 | 64 | PRs should have passing [GitHub status checks](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/collaborating-on-repositories-with-code-quality-features/about-status-checks) before review is requested (unless there are explicit questions asked in the PR about any failures). 65 | 66 | #### Asking Questions 67 | 68 | If you need help and/or have a question, posting a comment in the PR is a great way to do so. 69 | There's no need to tag anybody individually. 70 | One of us will drop by and help when we can. 71 | 72 | Please post comments as [line comments](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/commenting-on-a-pull-request#adding-line-comments-to-a-pull-request) when possible, so that they can be threaded. 73 | You can [resolve conversations](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/commenting-on-a-pull-request#resolving-conversations) on your own when you feel they're resolved - no need to comment explicitly and/or wait for a maintainer. 74 | 75 | #### Requested Changes 76 | 77 | After a maintainer reviews your PR, they may request changes on it. 78 | Once you've made those changes, [re-request review on GitHub](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/about-pull-request-reviews#re-requesting-a-review). 79 | 80 | Please try not to force-push commits to PRs that have already been reviewed. 81 | Doing so makes it harder to review the changes. 82 | We squash merge all commits so there's no need to try to preserve Git history within a PR branch. 83 | 84 | Once you've addressed all our feedback by making code changes and/or started a followup discussion, [re-request review](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/about-pull-request-reviews#re-requesting-a-review) from each maintainer whose feedback you addressed. 85 | 86 | Once all feedback is addressed and the PR is approved, we'll ensure the branch is up to date with `main` and merge it for you. 87 | 88 | #### Post-Merge Recognition 89 | 90 | Once your PR is merged, if you haven't yet been added to the [_Contributors_ table in the README.md](../README.md#contributors) for its [type of contribution](https://allcontributors.org/docs/en/emoji-key "Allcontributors emoji key"), you should be soon. 91 | Please do ping the maintainer who merged your PR if that doesn't happen within 24 hours - it was likely an oversight on our end! 92 | 93 | ## Emojis & Appreciation 94 | 95 | If you made it all the way to the end, bravo dear user, we love you. 96 | Please include an emoji in the bottom of your issues and PRs to signal to us that you did in fact read this file and are trying to conform to it as best as possible. 97 | ❤️‍🔥 is a good starter if you're not sure which to use. 98 | -------------------------------------------------------------------------------- /.github/DEVELOPMENT.md: -------------------------------------------------------------------------------- 1 | # Development 2 | 3 | After [forking the repo from GitHub](https://help.github.com/articles/fork-a-repo) and [installing pnpm](https://pnpm.io/installation): 4 | 5 | ```shell 6 | git clone https://github.com/(your-name-here)/flint 7 | cd flint 8 | pnpm install 9 | ``` 10 | 11 | > This repository includes a list of suggested VS Code extensions. 12 | > It's a good idea to use [VS Code](https://code.visualstudio.com) and accept its suggestion to install them, as they'll help with development. 13 | 14 | ## Building 15 | 16 | Run [**tsup**](https://tsup.egoist.dev) locally to build source files from `src/` into output files in `lib/`: 17 | 18 | ```shell 19 | pnpm build 20 | ``` 21 | 22 | Add `--watch` to run the builder in a watch mode that continuously cleans and recreates `lib/` as you save files: 23 | 24 | ```shell 25 | pnpm build --watch 26 | ``` 27 | 28 | ### Built App Debugging 29 | 30 | This repository includes a [VS Code launch configuration](https://code.visualstudio.com/docs/editor/debugging) for debugging. 31 | To debug a `bin` app, add a breakpoint to your code, then run _Debug Program_ from the VS Code Debug panel (or press F5). 32 | VS Code will automatically run the `build` task in the background before running `bin/index.js`. 33 | 34 | ## Formatting 35 | 36 | [Prettier](https://prettier.io) is used to format code. 37 | It should be applied automatically when you save files in VS Code or make a Git commit. 38 | 39 | To manually reformat all files, you can run: 40 | 41 | ```shell 42 | pnpm format --write 43 | ``` 44 | 45 | ## Linting 46 | 47 | This package includes several forms of linting to enforce consistent code quality and styling. 48 | Each should be shown in VS Code, and can be run manually on the command-line: 49 | 50 | - `pnpm lint` ([ESLint](https://eslint.org) with [typescript-eslint](https://typescript-eslint.io)): Lints JavaScript and TypeScript source files 51 | - `pnpm lint:knip` ([knip](https://github.com/webpro/knip)): Detects unused files, dependencies, and code exports 52 | - `pnpm lint:md` ([Markdownlint](https://github.com/DavidAnson/markdownlint)): Checks Markdown source files 53 | - `pnpm lint:packages` ([pnpm dedupe --check](https://pnpm.io/cli/dedupe)): Checks for unnecessarily duplicated packages in the `pnpm-lock.yml` file 54 | - `pnpm lint:spelling` ([cspell](https://cspell.org)): Spell checks across all source files 55 | 56 | Read the individual documentation for each linter to understand how it can be configured and used best. 57 | 58 | For example, ESLint can be run with `--fix` to auto-fix some lint rule complaints: 59 | 60 | ```shell 61 | pnpm run lint --fix 62 | ``` 63 | 64 | Note that you'll need to run `pnpm build` before `pnpm lint` so that lint rules which check the file system can pick up on any built files. 65 | 66 | ## Testing 67 | 68 | [Vitest](https://vitest.dev) is used for tests. 69 | You can run it locally on the command-line: 70 | 71 | ```shell 72 | pnpm run test 73 | ``` 74 | 75 | Add the `--coverage` flag to compute test coverage and place reports in the `coverage/` directory: 76 | 77 | ```shell 78 | pnpm run test --coverage 79 | ``` 80 | 81 | Note that [console-fail-test](https://github.com/JoshuaKGoldberg/console-fail-test) is enabled for all test runs. 82 | Calls to `console.log`, `console.warn`, and other console methods will cause a test to fail. 83 | 84 | ### Debugging Tests 85 | 86 | This repository includes a [VS Code launch configuration](https://code.visualstudio.com/docs/editor/debugging) for debugging unit tests. 87 | To launch it, open a test file, then run _Debug Current Test File_ from the VS Code Debug panel (or press F5). 88 | 89 | ## Type Checking 90 | 91 | You should be able to see suggestions from [TypeScript](https://typescriptlang.org) in your editor for all open files. 92 | 93 | However, it can be useful to run the TypeScript command-line (`tsc`) to type check all files in `src/`: 94 | 95 | ```shell 96 | pnpm tsc 97 | ``` 98 | 99 | Add `--watch` to keep the type checker running in a watch mode that updates the display as you save files: 100 | 101 | ```shell 102 | pnpm tsc --watch 103 | ``` 104 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ## Overview 8 | 9 | ... 10 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/01-bug.yml: -------------------------------------------------------------------------------- 1 | body: 2 | - attributes: 3 | description: If any of these required steps are not taken, we may not be able to review your issue. Help us to help you! 4 | label: Bug Report Checklist 5 | options: 6 | - label: I have tried restarting my IDE and the issue persists. 7 | required: true 8 | - label: I have pulled the latest `main` branch of the repository. 9 | required: true 10 | - label: I have [searched for related issues](https://github.com/JoshuaKGoldberg/flint/issues?q=is%3Aissue) and found none that matched my issue. 11 | required: true 12 | type: checkboxes 13 | - attributes: 14 | description: What did you expect to happen? 15 | label: Expected 16 | type: textarea 17 | validations: 18 | required: true 19 | - attributes: 20 | description: What happened instead? 21 | label: Actual 22 | type: textarea 23 | validations: 24 | required: true 25 | - attributes: 26 | description: Any additional info you'd like to provide. 27 | label: Additional Info 28 | type: textarea 29 | 30 | description: Report a bug trying to run the code 31 | 32 | labels: 33 | - "type: bug" 34 | 35 | name: 🐛 Bug 36 | 37 | title: "🐛 Bug: " 38 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/02-documentation.yml: -------------------------------------------------------------------------------- 1 | body: 2 | - attributes: 3 | description: If any of these required steps are not taken, we may not be able to review your issue. Help us to help you! 4 | label: Documentation Report Checklist 5 | options: 6 | - label: I have pulled the latest `main` branch of the repository. 7 | required: true 8 | - label: I have [searched for related issues](https://github.com/JoshuaKGoldberg/flint/issues?q=is%3Aissue) and found none that matched my issue. 9 | required: true 10 | type: checkboxes 11 | - attributes: 12 | description: What would you like to report? 13 | label: Overview 14 | type: textarea 15 | validations: 16 | required: true 17 | - attributes: 18 | description: Any additional info you'd like to provide. 19 | label: Additional Info 20 | type: textarea 21 | 22 | description: Report a typo or missing area of documentation 23 | 24 | labels: 25 | - "area: documentation" 26 | 27 | name: 📝 Documentation 28 | 29 | title: "📝 Documentation: " 30 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/03-feature.yml: -------------------------------------------------------------------------------- 1 | body: 2 | - attributes: 3 | description: If any of these required steps are not taken, we may not be able to review your issue. Help us to help you! 4 | label: Feature Request Checklist 5 | options: 6 | - label: I have pulled the latest `main` branch of the repository. 7 | required: true 8 | - label: I have [searched for related issues](https://github.com/JoshuaKGoldberg/flint/issues?q=is%3Aissue) and found none that matched my issue. 9 | required: true 10 | type: checkboxes 11 | - attributes: 12 | description: What did you expect to be able to do? 13 | label: Overview 14 | type: textarea 15 | validations: 16 | required: true 17 | - attributes: 18 | description: Any additional info you'd like to provide. 19 | label: Additional Info 20 | type: textarea 21 | 22 | description: Request that a new feature be added or an existing feature improved 23 | 24 | labels: 25 | - "type: feature" 26 | 27 | name: 🚀 Feature 28 | 29 | title: "🚀 Feature: " 30 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/04-tooling.yml: -------------------------------------------------------------------------------- 1 | body: 2 | - attributes: 3 | description: If any of these required steps are not taken, we may not be able to review your issue. Help us to help you! 4 | label: Tooling Report Checklist 5 | options: 6 | - label: I have tried restarting my IDE and the issue persists. 7 | required: true 8 | - label: I have pulled the latest `main` branch of the repository. 9 | required: true 10 | - label: I have [searched for related issues](https://github.com/JoshuaKGoldberg/flint/issues?q=is%3Aissue) and found none that matched my issue. 11 | required: true 12 | type: checkboxes 13 | - attributes: 14 | description: What did you expect to be able to do? 15 | label: Overview 16 | type: textarea 17 | validations: 18 | required: true 19 | - attributes: 20 | description: Any additional info you'd like to provide. 21 | label: Additional Info 22 | type: textarea 23 | 24 | description: Report a bug or request an enhancement in repository tooling 25 | 26 | labels: 27 | - "area: tooling" 28 | 29 | name: 🛠 Tooling 30 | 31 | title: "🛠 Tooling: " 32 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 4 | 5 | ## PR Checklist 6 | 7 | - [ ] Addresses an existing open issue: fixes #000 8 | - [ ] That issue was marked as [`status: accepting prs`](https://github.com/JoshuaKGoldberg/flint/issues?q=is%3Aopen+is%3Aissue+label%3A%22status%3A+accepting+prs%22) 9 | - [ ] Steps in [CONTRIBUTING.md](https://github.com/JoshuaKGoldberg/flint/blob/main/.github/CONTRIBUTING.md) were taken 10 | 11 | ## Overview 12 | 13 | 14 | -------------------------------------------------------------------------------- /.github/SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | We take all security vulnerabilities seriously. 4 | If you have a vulnerability or other security issues to disclose: 5 | 6 | - Thank you very much, please do! 7 | - Please send them to us by emailing `git@joshuakgoldberg.com` 8 | 9 | We appreciate your efforts and responsible disclosure and will make every effort to acknowledge your contributions. 10 | -------------------------------------------------------------------------------- /.github/actions/prepare/action.yml: -------------------------------------------------------------------------------- 1 | description: Prepares the repo for a typical CI job 2 | 3 | name: Prepare 4 | 5 | runs: 6 | steps: 7 | - uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4 8 | - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 9 | with: 10 | cache: pnpm 11 | node-version: 24.1.0 12 | - run: pnpm install --frozen-lockfile 13 | shell: bash 14 | using: composite 15 | -------------------------------------------------------------------------------- /.github/renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "automerge": true, 4 | "extends": [ 5 | ":preserveSemverRanges", 6 | "config:best-practices", 7 | "replacements:all" 8 | ], 9 | "ignoreDeps": ["codecov/codecov-action"], 10 | "labels": ["dependencies"], 11 | "minimumReleaseAge": "7 days", 12 | "patch": { "enabled": false }, 13 | "postUpdateOptions": ["pnpmDedupe"] 14 | } 15 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | jobs: 2 | build: 3 | name: Build 4 | runs-on: ubuntu-latest 5 | steps: 6 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 7 | - uses: ./.github/actions/prepare 8 | - run: pnpm build 9 | - run: node lib/index.js 10 | lint: 11 | name: Lint 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 15 | - uses: ./.github/actions/prepare 16 | - run: pnpm build 17 | - run: pnpm lint 18 | lint_knip: 19 | name: Lint Knip 20 | runs-on: ubuntu-latest 21 | steps: 22 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 23 | - uses: ./.github/actions/prepare 24 | - run: pnpm lint:knip 25 | lint_markdown: 26 | name: Lint Markdown 27 | runs-on: ubuntu-latest 28 | steps: 29 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 30 | - uses: ./.github/actions/prepare 31 | - run: pnpm lint:md 32 | lint_packages: 33 | name: Lint Packages 34 | runs-on: ubuntu-latest 35 | steps: 36 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 37 | - uses: ./.github/actions/prepare 38 | - run: pnpm lint:packages 39 | lint_spelling: 40 | name: Lint Spelling 41 | runs-on: ubuntu-latest 42 | steps: 43 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 44 | - uses: ./.github/actions/prepare 45 | - run: pnpm lint:spelling 46 | prettier: 47 | name: Prettier 48 | runs-on: ubuntu-latest 49 | steps: 50 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 51 | - uses: ./.github/actions/prepare 52 | - run: pnpm format --list-different 53 | test: 54 | name: Test 55 | runs-on: ubuntu-latest 56 | steps: 57 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 58 | - uses: ./.github/actions/prepare 59 | - run: pnpm run test --coverage 60 | - env: 61 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 62 | if: always() 63 | uses: codecov/codecov-action@v3 64 | type_check: 65 | name: Type Check 66 | runs-on: ubuntu-latest 67 | steps: 68 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 69 | - uses: ./.github/actions/prepare 70 | - run: pnpm tsc 71 | 72 | name: CI 73 | 74 | on: 75 | pull_request: ~ 76 | push: 77 | branches: 78 | - main 79 | -------------------------------------------------------------------------------- /.github/workflows/contributors.yml: -------------------------------------------------------------------------------- 1 | jobs: 2 | contributors: 3 | runs-on: ubuntu-latest 4 | steps: 5 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 6 | with: 7 | fetch-depth: 0 8 | - uses: ./.github/actions/prepare 9 | - env: 10 | GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }} 11 | uses: JoshuaKGoldberg/all-contributors-auto-action@944abe4387e751b5bbb38616cb25cf4a4ca998f2 # v0.5.0 12 | 13 | name: Contributors 14 | 15 | on: 16 | push: 17 | branches: 18 | - main 19 | -------------------------------------------------------------------------------- /.github/workflows/octoguide.yml: -------------------------------------------------------------------------------- 1 | jobs: 2 | octoguide: 3 | if: ${{ !endsWith(github.actor, '[bot]') }} 4 | runs-on: ubuntu-latest 5 | steps: 6 | - uses: JoshuaKGoldberg/octoguide@c715c04e9b9a30f2a12a487d40cd1049e64549d9 # 0.11.1 7 | with: 8 | config: strict 9 | github-token: ${{ secrets.GITHUB_TOKEN }} 10 | 11 | name: OctoGuide 12 | 13 | on: 14 | discussion: 15 | types: 16 | - created 17 | - edited 18 | discussion_comment: 19 | types: 20 | - created 21 | - deleted 22 | - edited 23 | issue_comment: 24 | types: 25 | - created 26 | - deleted 27 | - edited 28 | issues: 29 | types: 30 | - edited 31 | - opened 32 | pull_request_review_comment: 33 | types: 34 | - created 35 | - deleted 36 | - edited 37 | pull_request_target: 38 | types: 39 | - edited 40 | - opened 41 | 42 | permissions: 43 | discussions: write 44 | issues: write 45 | pull-requests: write 46 | -------------------------------------------------------------------------------- /.github/workflows/post-release.yml: -------------------------------------------------------------------------------- 1 | jobs: 2 | post_release: 3 | runs-on: ubuntu-latest 4 | steps: 5 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 6 | with: 7 | fetch-depth: 0 8 | - run: echo "npm_version=$(npm pkg get version | tr -d '"')" >> "$GITHUB_ENV" 9 | - uses: apexskier/github-release-commenter@3bd413ad5e1d603bfe2282f9f06f2bdcec079327 # v1 10 | with: 11 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 12 | comment-template: | 13 | :tada: This is included in version {release_link} :tada: 14 | 15 | The release is available on: 16 | 17 | * [GitHub releases](https://github.com/JoshuaKGoldberg/flint/releases/tag/{release_tag}) 18 | * [npm package (@latest dist-tag)](https://www.npmjs.com/package/flint/v/${{ env.npm_version }}) 19 | 20 | Cheers! 📦🚀 21 | 22 | name: Post Release 23 | 24 | on: 25 | release: 26 | types: 27 | - published 28 | 29 | permissions: 30 | issues: write 31 | pull-requests: write 32 | -------------------------------------------------------------------------------- /.github/workflows/pr-review-requested.yml: -------------------------------------------------------------------------------- 1 | jobs: 2 | pr_review_requested: 3 | runs-on: ubuntu-latest 4 | steps: 5 | - uses: actions-ecosystem/action-remove-labels@2ce5d41b4b6aa8503e285553f75ed56e0a40bae0 # v1 6 | with: 7 | labels: "status: waiting for author" 8 | - if: failure() 9 | run: | 10 | echo "Don't worry if the previous step failed." 11 | echo "See https://github.com/actions-ecosystem/action-remove-labels/issues/221." 12 | 13 | name: PR Review Requested 14 | 15 | on: 16 | pull_request_target: 17 | types: 18 | - review_requested 19 | 20 | permissions: 21 | pull-requests: write 22 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | concurrency: 2 | group: ${{ github.workflow }} 3 | 4 | jobs: 5 | release: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4 9 | with: 10 | fetch-depth: 0 11 | ref: main 12 | token: ${{ secrets.ACCESS_TOKEN }} 13 | - uses: ./.github/actions/prepare 14 | - run: pnpm build 15 | - env: 16 | GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }} 17 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 18 | uses: JoshuaKGoldberg/release-it-action@dc71f396c291f62f9a17701cfc4d4a3e7c263020 # v0.3.2 19 | 20 | name: Release 21 | 22 | on: 23 | push: 24 | branches: 25 | - main 26 | 27 | permissions: 28 | contents: write 29 | id-token: write 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /coverage 2 | /lib 3 | /node_modules 4 | /tsconfig.vitest-temp.json 5 | -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | npx lint-staged 2 | -------------------------------------------------------------------------------- /.markdownlint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "markdownlint/style/prettier", 3 | "first-line-h1": false, 4 | "no-inline-html": false 5 | } 6 | -------------------------------------------------------------------------------- /.markdownlintignore: -------------------------------------------------------------------------------- 1 | .github/CODE_OF_CONDUCT.md 2 | CHANGELOG.md 3 | lib/ 4 | node_modules/ 5 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 24.1.0 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | /.all-contributorsrc 2 | /.husky 3 | /coverage 4 | /lib 5 | /pnpm-lock.yaml 6 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/prettierrc", 3 | "overrides": [{ "files": ".nvmrc", "options": { "parser": "yaml" } }], 4 | "plugins": [ 5 | "prettier-plugin-curly", 6 | "prettier-plugin-packagejson", 7 | "prettier-plugin-sh" 8 | ], 9 | "useTabs": true 10 | } 11 | -------------------------------------------------------------------------------- /.release-it.json: -------------------------------------------------------------------------------- 1 | { 2 | "git": { 3 | "commitMessage": "chore: release v${version}", 4 | "requireCommits": true 5 | }, 6 | "github": { "release": true, "releaseName": "v${version}" }, 7 | "npm": { "publishArgs": ["--access public", "--provenance"] }, 8 | "plugins": { 9 | "@release-it/conventional-changelog": { 10 | "infile": "CHANGELOG.md", 11 | "preset": "angular", 12 | "types": [ 13 | { "section": "Features", "type": "feat" }, 14 | { "section": "Bug Fixes", "type": "fix" }, 15 | { "section": "Performance Improvements", "type": "perf" }, 16 | { "hidden": true, "type": "build" }, 17 | { "hidden": true, "type": "chore" }, 18 | { "hidden": true, "type": "ci" }, 19 | { "hidden": true, "type": "docs" }, 20 | { "hidden": true, "type": "refactor" }, 21 | { "hidden": true, "type": "style" }, 22 | { "hidden": true, "type": "test" } 23 | ] 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "DavidAnson.vscode-markdownlint", 4 | "dbaeumer.vscode-eslint", 5 | "esbenp.prettier-vscode", 6 | "streetsidesoftware.code-spell-checker", 7 | "vitest.explorer" 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "args": ["run", "${relativeFile}"], 5 | "autoAttachChildProcesses": true, 6 | "console": "integratedTerminal", 7 | "name": "Debug Current Test File", 8 | "program": "${workspaceRoot}/node_modules/vitest/vitest.mjs", 9 | "request": "launch", 10 | "skipFiles": ["/**", "**/node_modules/**"], 11 | "smartStep": true, 12 | "type": "node" 13 | }, 14 | { 15 | "name": "Debug Program", 16 | "preLaunchTask": "build", 17 | "program": "bin/index.js", 18 | "request": "launch", 19 | "skipFiles": ["/**"], 20 | "type": "node" 21 | } 22 | ], 23 | "version": "0.2.0" 24 | } 25 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.codeActionsOnSave": { "source.fixAll.eslint": "explicit" }, 3 | "editor.defaultFormatter": "esbenp.prettier-vscode", 4 | "editor.formatOnSave": true, 5 | "editor.rulers": [80], 6 | "eslint.probe": [ 7 | "javascript", 8 | "javascriptreact", 9 | "json", 10 | "jsonc", 11 | "markdown", 12 | "typescript", 13 | "typescriptreact", 14 | "yaml" 15 | ], 16 | "eslint.rules.customizations": [{ "rule": "*", "severity": "warn" }], 17 | "typescript.tsdk": "node_modules/typescript/lib" 18 | } 19 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": [ 3 | { 4 | "detail": "Build the project", 5 | "label": "build", 6 | "script": "build", 7 | "type": "npm" 8 | } 9 | ], 10 | "version": "2.0.0" 11 | } 12 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | # [0.3.0](https://github.com/JoshuaKGoldberg/flint/compare/0.2.0...0.3.0) (2025-05-22) 4 | 5 | ### Features 6 | 7 | - rules with options or type checking, with passing unit tests ([e6aa4f5](https://github.com/JoshuaKGoldberg/flint/commit/e6aa4f5dadb27dccbd89499049a54fd8d5915f51)) 8 | 9 | # 0.2.0 (2025-05-22) 10 | 11 | ### Bug Fixes 12 | 13 | - add bin and correct README.md from template ([6a0eefa](https://github.com/JoshuaKGoldberg/flint/commit/6a0eefa3e8e625704b0bb547bf5c83512388974f)) 14 | - bump package to 0.1.0, so it'll publish as 0.1.1 ([84014be](https://github.com/JoshuaKGoldberg/flint/commit/84014beb2ab4da1fc7b23cb8a0fc113bbbcb5c52)) 15 | 16 | ### Features 17 | 18 | - initialized repo ✨ ([f411df5](https://github.com/JoshuaKGoldberg/flint/commit/f411df5890399bc62e1794e6839562e6c1bd131d)) 19 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | 'Software'), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 17 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 18 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 19 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 20 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Flint

2 | 3 |

4 | A fast, friendly linter. 5 | ❤️‍🔥 6 |

7 | 8 |

9 | 10 | 11 | 👪 All Contributors: 1 12 | 13 | 14 | 🤝 Code of Conduct: Kept 15 | 🧪 Coverage 16 | 📝 License: MIT 17 | 📦 npm version 18 | 💪 TypeScript: Strict 19 |

20 | 21 | Cartoon campfire - caption: (experimental) 22 | 23 | **Flint** is an experimental new linter. 24 | It's a proof-of-concept to explore the concepts in the following blog posts: 25 | 26 | - [Hybrid Linters: The Best of Both Worlds](https://www.joshuakgoldberg.com/blog/hybrid-linters-the-best-of-both-worlds) 27 | - [If I Wrote a Linter, Part 1: Architecture](https://www.joshuakgoldberg.com/blog/if-i-wrote-a-linter-part-1-architecture) 28 | - [If I Wrote a Linter, Part 2: Developer Experience](https://www.joshuakgoldberg.com/blog/if-i-wrote-a-linter-part-2-developer-experience) 29 | - [If I Wrote a Linter, Part 3: Ecosystem](https://www.joshuakgoldberg.com/blog/if-i-wrote-a-linter-part-3-ecosystem) 30 | 31 | This project might go nowhere. 32 | It might show some of those ideas to be wrong. 33 | It might become a real linter. 34 | Only time will tell. 35 | 36 | ## Usage 37 | 38 | Coming soon. 39 | 40 | ## Development 41 | 42 | See [`.github/CONTRIBUTING.md`](./.github/CONTRIBUTING.md), then [`.github/DEVELOPMENT.md`](./.github/DEVELOPMENT.md). 43 | Thanks! ❤️‍🔥 44 | 45 | ## Contributors 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 |
Josh Goldberg ✨
Josh Goldberg ✨

💻 🖋 📖 🤔 🚇 🚧 📆 🔧
58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | > 💝 This package was templated with [`create-typescript-app`](https://github.com/JoshuaKGoldberg/create-typescript-app) using the [Bingo framework](https://create.bingo). 66 | -------------------------------------------------------------------------------- /bin/index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | console.log("Hello, world!"); 3 | -------------------------------------------------------------------------------- /cspell.json: -------------------------------------------------------------------------------- 1 | { 2 | "dictionaries": ["npm", "node", "typescript"], 3 | "ignorePaths": [ 4 | ".all-contributorsrc", 5 | ".github", 6 | "CHANGELOG.md", 7 | "coverage", 8 | "lib", 9 | "node_modules", 10 | "pnpm-lock.yaml" 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /docs/flint.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JoshuaKGoldberg/flint/ac6ccffce4ef3490be1e021af69510f725976618/docs/flint.png -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | import comments from "@eslint-community/eslint-plugin-eslint-comments/configs"; 2 | import eslint from "@eslint/js"; 3 | import vitest from "@vitest/eslint-plugin"; 4 | import jsdoc from "eslint-plugin-jsdoc"; 5 | import jsonc from "eslint-plugin-jsonc"; 6 | import markdown from "eslint-plugin-markdown"; 7 | import n from "eslint-plugin-n"; 8 | import packageJson from "eslint-plugin-package-json"; 9 | import perfectionist from "eslint-plugin-perfectionist"; 10 | import * as regexp from "eslint-plugin-regexp"; 11 | import yml from "eslint-plugin-yml"; 12 | import tseslint from "typescript-eslint"; 13 | 14 | export default tseslint.config( 15 | { 16 | ignores: ["**/*.snap", "coverage", "lib", "node_modules", "pnpm-lock.yaml"], 17 | }, 18 | { linterOptions: { reportUnusedDisableDirectives: "error" } }, 19 | eslint.configs.recommended, 20 | comments.recommended, 21 | jsdoc.configs["flat/contents-typescript-error"], 22 | jsdoc.configs["flat/logical-typescript-error"], 23 | jsdoc.configs["flat/stylistic-typescript-error"], 24 | jsonc.configs["flat/recommended-with-json"], 25 | markdown.configs.recommended, 26 | n.configs["flat/recommended"], 27 | packageJson.configs.recommended, 28 | perfectionist.configs["recommended-natural"], 29 | regexp.configs["flat/recommended"], 30 | { 31 | extends: [ 32 | tseslint.configs.strictTypeChecked, 33 | tseslint.configs.stylisticTypeChecked, 34 | ], 35 | files: ["**/*.{js,ts}"], 36 | languageOptions: { 37 | parserOptions: { 38 | projectService: { 39 | allowDefaultProject: ["*.config.*s", "bin/index.js"], 40 | }, 41 | tsconfigRootDir: import.meta.dirname, 42 | }, 43 | }, 44 | rules: { 45 | // Stylistic concerns that don't interfere with Prettier 46 | "logical-assignment-operators": [ 47 | "error", 48 | "always", 49 | { enforceForIfStatements: true }, 50 | ], 51 | "no-useless-rename": "error", 52 | "object-shorthand": "error", 53 | "operator-assignment": "error", 54 | }, 55 | settings: { 56 | perfectionist: { partitionByComment: true, type: "natural" }, 57 | vitest: { typecheck: true }, 58 | }, 59 | }, 60 | { 61 | extends: [tseslint.configs.disableTypeChecked], 62 | files: ["**/*.md/*.ts"], 63 | rules: { "n/no-missing-import": "off" }, 64 | }, 65 | { 66 | extends: [vitest.configs.recommended], 67 | files: ["**/*.test.*"], 68 | rules: { "@typescript-eslint/no-unsafe-assignment": "off" }, 69 | }, 70 | { 71 | extends: [yml.configs["flat/standard"], yml.configs["flat/prettier"]], 72 | files: ["**/*.{yml,yaml}"], 73 | rules: { 74 | "yml/file-extension": ["error", { extension: "yml" }], 75 | "yml/sort-keys": [ 76 | "error", 77 | { order: { type: "asc" }, pathPattern: "^.*$" }, 78 | ], 79 | "yml/sort-sequence-values": [ 80 | "error", 81 | { order: { type: "asc" }, pathPattern: "^.*$" }, 82 | ], 83 | }, 84 | }, 85 | ); 86 | -------------------------------------------------------------------------------- /knip.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://unpkg.com/knip@5.46.0/schema.json", 3 | "entry": ["src/**/*.test.*", "src/index.ts"], 4 | "ignoreExportsUsedInFile": { "interface": true, "type": true }, 5 | "project": ["src/**/*.ts"] 6 | } 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "flint", 3 | "version": "0.3.0", 4 | "description": "A fast, friendly linter. ❤️‍🔥", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/JoshuaKGoldberg/flint.git" 8 | }, 9 | "license": "MIT", 10 | "author": { 11 | "name": "Josh Goldberg ✨", 12 | "email": "npm@joshuakgoldberg.com" 13 | }, 14 | "type": "module", 15 | "main": "lib/index.js", 16 | "bin": "bin/index.js", 17 | "files": [ 18 | "LICENSE.md", 19 | "README.md", 20 | "bin/index.js", 21 | "lib/", 22 | "package.json" 23 | ], 24 | "scripts": { 25 | "build": "tsup", 26 | "format": "prettier .", 27 | "lint": "eslint . --max-warnings 0", 28 | "lint:knip": "knip", 29 | "lint:md": "markdownlint \"**/*.md\" \".github/**/*.md\" --rules sentences-per-line", 30 | "lint:packages": "pnpm dedupe --check", 31 | "lint:spelling": "cspell \"**\" \".github/**/*\"", 32 | "prepare": "husky", 33 | "test": "vitest --typecheck", 34 | "tsc": "tsc" 35 | }, 36 | "lint-staged": { 37 | "*": "prettier --ignore-unknown --write" 38 | }, 39 | "dependencies": { 40 | "@typescript/vfs": "^1.6.1", 41 | "cached-factory": "^0.1.0", 42 | "ts-api-utils": "^2.1.0", 43 | "zod": "^3.25.20" 44 | }, 45 | "devDependencies": { 46 | "@eslint-community/eslint-plugin-eslint-comments": "4.5.0", 47 | "@eslint/js": "9.27.0", 48 | "@release-it/conventional-changelog": "10.0.0", 49 | "@types/eslint-plugin-markdown": "2.0.2", 50 | "@types/node": "22.15.18", 51 | "@vitest/coverage-v8": "3.1.3", 52 | "@vitest/eslint-plugin": "1.2.0", 53 | "console-fail-test": "0.5.0", 54 | "cspell": "9.0.1", 55 | "eslint": "9.27.0", 56 | "eslint-plugin-jsdoc": "50.6.8", 57 | "eslint-plugin-jsonc": "2.20.0", 58 | "eslint-plugin-markdown": "5.1.0", 59 | "eslint-plugin-n": "17.18.0", 60 | "eslint-plugin-package-json": "0.31.0", 61 | "eslint-plugin-perfectionist": "4.13.0", 62 | "eslint-plugin-regexp": "2.7.0", 63 | "eslint-plugin-yml": "1.18.0", 64 | "husky": "9.1.7", 65 | "knip": "5.58.0", 66 | "lint-staged": "16.0.0", 67 | "markdownlint": "0.38.0", 68 | "markdownlint-cli": "0.45.0", 69 | "prettier": "3.5.3", 70 | "prettier-plugin-curly": "0.3.1", 71 | "prettier-plugin-packagejson": "2.5.10", 72 | "prettier-plugin-sh": "0.17.4", 73 | "release-it": "19.0.2", 74 | "sentences-per-line": "0.3.0", 75 | "tsup": "8.5.0", 76 | "typescript": "5.8.2", 77 | "typescript-eslint": "8.32.1", 78 | "vitest": "3.1.3" 79 | }, 80 | "peerDependencies": { 81 | "typescript": ">=5.8.0" 82 | }, 83 | "packageManager": "pnpm@10.11.0", 84 | "engines": { 85 | "node": ">=24.0.0" 86 | }, 87 | "publishConfig": { 88 | "provenance": true 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/createRule.ts: -------------------------------------------------------------------------------- 1 | import { RuleAbout, RuleDefinition } from "./types/rules.js"; 2 | import { AnyOptionalSchema } from "./types/shapes.js"; 3 | 4 | export function createRule< 5 | const About extends RuleAbout, 6 | const Message extends string, 7 | >(definition: RuleDefinition): typeof definition; 8 | export function createRule< 9 | const About extends RuleAbout, 10 | const Message extends string, 11 | const OptionsSchema extends AnyOptionalSchema, 12 | >(definition: RuleDefinition): typeof definition; 13 | export function createRule< 14 | const About extends RuleAbout, 15 | const Message extends string, 16 | const OptionsSchema extends AnyOptionalSchema | undefined, 17 | >(definition: RuleDefinition) { 18 | return definition; 19 | } 20 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { createRule } from "./createRule.js"; 2 | export { ts } from "./plugin.js"; 3 | export { createPlugin } from "./plugins/createPlugin.js"; 4 | export { RuleTester } from "./testing/RuleTester.js"; 5 | -------------------------------------------------------------------------------- /src/plugin.ts: -------------------------------------------------------------------------------- 1 | import { createPlugin } from "./plugins/createPlugin.js"; 2 | import consecutiveNonNullAssertions from "./rules/consecutiveNonNullAssertions.js"; 3 | import forInArrays from "./rules/forInArrays.js"; 4 | import namespaceDeclarations from "./rules/namespaceDeclarations.js"; 5 | 6 | export const ts = createPlugin({ 7 | name: "ts", 8 | rules: [forInArrays, consecutiveNonNullAssertions, namespaceDeclarations], 9 | }); 10 | -------------------------------------------------------------------------------- /src/plugins/createPlugin.test-d.ts: -------------------------------------------------------------------------------- 1 | import { describe, it, vi } from "vitest"; 2 | import z from "zod"; 3 | 4 | import { createRule } from "../createRule.js"; 5 | import { createPlugin } from "./createPlugin.js"; 6 | 7 | const ruleStandalone = createRule({ 8 | about: { 9 | id: "standalone", 10 | }, 11 | messages: { "": "" }, 12 | setup: vi.fn(), 13 | }); 14 | 15 | const ruleWithOptionalOption = createRule({ 16 | about: { 17 | id: "withOptionalOption", 18 | }, 19 | messages: { "": "" }, 20 | options: { 21 | value: z.string().optional(), 22 | }, 23 | setup: vi.fn(), 24 | }); 25 | 26 | describe(createPlugin, () => { 27 | const plugin = createPlugin({ 28 | name: "test", 29 | rules: [ruleStandalone, ruleWithOptionalOption], 30 | }); 31 | 32 | describe("rules", () => { 33 | it("produces a type error when a rule option is the wrong type", () => { 34 | plugin.rules({ 35 | withOptionalOption: { 36 | // @ts-expect-error -- This should report that a string is required 37 | value: 123, 38 | }, 39 | }); 40 | }); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /src/plugins/createPlugin.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it, vi } from "vitest"; 2 | import z from "zod"; 3 | 4 | import { createRule } from "../createRule.js"; 5 | import { createPlugin } from "./createPlugin.js"; 6 | 7 | const ruleStandalone = createRule({ 8 | about: { 9 | id: "standalone", 10 | preset: "first", 11 | }, 12 | messages: { "": "" }, 13 | setup: vi.fn(), 14 | }); 15 | 16 | const ruleWithOptionalOption = createRule({ 17 | about: { 18 | id: "withOptionalOption", 19 | preset: "second", 20 | }, 21 | messages: { "": "" }, 22 | options: { 23 | value: z.string().optional(), 24 | }, 25 | setup: vi.fn(), 26 | }); 27 | 28 | describe(createPlugin, () => { 29 | const plugin = createPlugin({ 30 | name: "test", 31 | rules: [ruleStandalone, ruleWithOptionalOption], 32 | }); 33 | 34 | describe("presets", () => { 35 | it("groups rules by about.preset when it exists", () => { 36 | expect(plugin.presets).toEqual({ 37 | first: [ruleStandalone], 38 | second: [ruleWithOptionalOption], 39 | }); 40 | }); 41 | }); 42 | 43 | describe("rules", () => { 44 | it("returns a rule with options when specified with an option", () => { 45 | const value = "abc"; 46 | const rules = plugin.rules({ 47 | withOptionalOption: { value }, 48 | }); 49 | 50 | expect(rules).toEqual([ 51 | { 52 | options: { value }, 53 | rule: ruleWithOptionalOption, 54 | }, 55 | ]); 56 | }); 57 | }); 58 | }); 59 | -------------------------------------------------------------------------------- /src/plugins/createPlugin.ts: -------------------------------------------------------------------------------- 1 | import { Plugin, PluginPresets } from "../types/plugins.js"; 2 | import { RuleAbout, RuleDefinition } from "../types/rules.js"; 3 | import { AnyOptionalSchema } from "../types/shapes.js"; 4 | 5 | export interface CreatePluginOptions< 6 | About extends RuleAbout, 7 | Rules extends RuleDefinition[], 8 | > { 9 | name: string; 10 | rules: Rules; 11 | } 12 | 13 | export function createPlugin< 14 | const About extends RuleAbout, 15 | // TODO: How to properly constrain this type parameter? 16 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 17 | const Rules extends RuleDefinition[], 18 | >({ name, rules }: CreatePluginOptions): Plugin { 19 | const presets = Object.groupBy( 20 | rules.filter((rule) => typeof rule.about.preset === "string"), 21 | // TODO: Figure out inferred type predicate... 22 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 23 | (rule) => rule.about.preset!, 24 | ) as PluginPresets; 25 | 26 | const rulesById = new Map(rules.map((rule) => [rule.about.id, rule])); 27 | 28 | return { 29 | name, 30 | presets, 31 | // @ts-expect-error -- TODO: Figure out what to assert...? 32 | rules: (configuration) => { 33 | return Object.entries(configuration).map(([id, options]) => ({ 34 | options, 35 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 36 | rule: rulesById.get(id)!, 37 | })); 38 | }, 39 | }; 40 | } 41 | -------------------------------------------------------------------------------- /src/rules/consecutiveNonNullAssertions.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, it } from "vitest"; 2 | 3 | import { RuleTester } from "../testing/RuleTester.js"; 4 | import rule from "./consecutiveNonNullAssertions.js"; 5 | 6 | const ruleTester = new RuleTester({ 7 | describe, 8 | it, 9 | }); 10 | 11 | ruleTester.describe(rule, { 12 | invalid: [ 13 | { 14 | code: ` 15 | declare const outer: { inner: number } | null; 16 | outer!!.inner; 17 | `, 18 | output: ` 19 | declare const outer: { inner: number } | null; 20 | outer!.inner; 21 | `, 22 | snapshot: ` 23 | declare const outer: { inner: number } | null; 24 | outer!!.inner; 25 | ~~ 26 | Unnecessary consecutive non-null assertion operator. 27 | `, 28 | }, 29 | ], 30 | valid: [ 31 | ` 32 | declare const outer: { inner: number } | null; 33 | outer!.inner; 34 | `, 35 | ` 36 | declare const outer: { inner: number } | null; 37 | outer?.inner!; 38 | `, 39 | ], 40 | }); 41 | -------------------------------------------------------------------------------- /src/rules/consecutiveNonNullAssertions.ts: -------------------------------------------------------------------------------- 1 | import * as ts from "typescript"; 2 | 3 | import { createRule } from "../createRule.js"; 4 | 5 | export default createRule({ 6 | about: { 7 | id: "consecutiveNonNullAssertions", 8 | preset: "logical", 9 | }, 10 | messages: { 11 | consecutiveNonNullAssertion: 12 | "Unnecessary consecutive non-null assertion operator.", 13 | }, 14 | setup(context) { 15 | return { 16 | NonNullExpression(node) { 17 | if (node.parent.kind === ts.SyntaxKind.NonNullExpression) { 18 | context.report({ 19 | message: "consecutiveNonNullAssertion", 20 | range: { 21 | begin: node.end, 22 | end: node.parent.end + 1, 23 | }, 24 | }); 25 | } 26 | }, 27 | }; 28 | }, 29 | }); 30 | -------------------------------------------------------------------------------- /src/rules/forInArrays.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, it } from "vitest"; 2 | 3 | import { RuleTester } from "../testing/RuleTester.js"; 4 | import rule from "./forInArrays.js"; 5 | 6 | const ruleTester = new RuleTester({ 7 | describe, 8 | it, 9 | }); 10 | 11 | ruleTester.describe(rule, { 12 | invalid: [ 13 | { 14 | code: ` 15 | declare const array: string[]; 16 | for (const i in array) {} 17 | `, 18 | snapshot: ` 19 | declare const array: string[]; 20 | for (const i in array) {} 21 | ~~~~~~~~~~~~~~~~~~~~~~ 22 | Avoid using for-in loops over arrays, as they have surprising behavior that often leads to bugs. 23 | `, 24 | }, 25 | ], 26 | valid: [ 27 | ` 28 | declare const array: string[]; 29 | for (const i of array) {} 30 | `, 31 | ], 32 | }); 33 | -------------------------------------------------------------------------------- /src/rules/forInArrays.ts: -------------------------------------------------------------------------------- 1 | import * as tsutils from "ts-api-utils"; 2 | import * as ts from "typescript"; 3 | 4 | import { createRule } from "../createRule.js"; 5 | import { getConstrainedTypeAtLocation } from "./utils/getConstrainedType.js"; 6 | import { isTypeRecursive } from "./utils/isTypeRecursive.js"; 7 | 8 | export default createRule({ 9 | about: { 10 | id: "forInArrays", 11 | preset: "logical", 12 | }, 13 | messages: { 14 | preferModules: 15 | "Avoid using for-in loops over arrays, as they have surprising behavior that often leads to bugs.", 16 | }, 17 | setup(context) { 18 | function hasNumberLikeLength(type: ts.Type): boolean { 19 | const lengthProperty = type.getProperty("length"); 20 | 21 | if (lengthProperty == null) { 22 | return false; 23 | } 24 | 25 | return tsutils.isTypeFlagSet( 26 | context.typeChecker.getTypeOfSymbol(lengthProperty), 27 | ts.TypeFlags.NumberLike, 28 | ); 29 | } 30 | 31 | function isArrayLike(type: ts.Type): boolean { 32 | return isTypeRecursive( 33 | type, 34 | (t) => t.getNumberIndexType() != null && hasNumberLikeLength(t), 35 | ); 36 | } 37 | 38 | return { 39 | ForInStatement(node) { 40 | const type = getConstrainedTypeAtLocation( 41 | node.expression, 42 | context.typeChecker, 43 | ); 44 | 45 | if (isArrayLike(type)) { 46 | context.report({ 47 | message: "preferModules", 48 | range: { 49 | begin: node.getStart(), 50 | end: node.statement.getStart() - 1, 51 | }, 52 | }); 53 | } 54 | }, 55 | }; 56 | }, 57 | }); 58 | -------------------------------------------------------------------------------- /src/rules/namespaceDeclarations.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, it } from "vitest"; 2 | 3 | import { RuleTester } from "../testing/RuleTester.js"; 4 | import rule from "./namespaceDeclarations.js"; 5 | 6 | const ruleTester = new RuleTester({ 7 | describe, 8 | it, 9 | }); 10 | 11 | ruleTester.describe(rule, { 12 | invalid: [ 13 | { 14 | code: ` 15 | namespace name {} 16 | `, 17 | snapshot: ` 18 | namespace name {} 19 | ~~~~~~~~~ 20 | Prefer using ECMAScript modules over legacy TypeScript namespaces. 21 | `, 22 | }, 23 | ], 24 | valid: [ 25 | `declare global {}`, 26 | `declare module 'name' {}`, 27 | { 28 | code: `declare module name {}`, 29 | options: { allowDeclarations: true }, 30 | }, 31 | { 32 | code: `declare namespace name {}`, 33 | options: { allowDeclarations: true }, 34 | }, 35 | { 36 | code: ` 37 | declare namespace outer { 38 | namespace inner {} 39 | }`, 40 | options: { allowDeclarations: true }, 41 | }, 42 | { 43 | code: `namespace name {}`, 44 | fileName: "file.d.ts", 45 | options: { allowDefinitionFiles: true }, 46 | }, 47 | ], 48 | }); 49 | -------------------------------------------------------------------------------- /src/rules/namespaceDeclarations.ts: -------------------------------------------------------------------------------- 1 | import * as tsutils from "ts-api-utils"; 2 | import * as ts from "typescript"; 3 | import { z } from "zod"; 4 | 5 | import { createRule } from "../createRule.js"; 6 | 7 | export default createRule({ 8 | about: { 9 | id: "namespaceDeclarations", 10 | preset: "logical", 11 | }, 12 | messages: { 13 | preferModules: 14 | "Prefer using ECMAScript modules over legacy TypeScript namespaces.", 15 | }, 16 | options: { 17 | allowDeclarations: z.boolean().default(false), 18 | allowDefinitionFiles: z.boolean().default(false), 19 | }, 20 | setup(context, { allowDeclarations, allowDefinitionFiles }) { 21 | if (allowDefinitionFiles && context.sourceFile.isDeclarationFile) { 22 | return; 23 | } 24 | 25 | return { 26 | ModuleDeclaration(node) { 27 | if ( 28 | node.parent.kind !== ts.SyntaxKind.SourceFile || 29 | node.name.kind !== ts.SyntaxKind.Identifier || 30 | node.name.text === "global" 31 | ) { 32 | return; 33 | } 34 | 35 | if ( 36 | allowDeclarations && 37 | tsutils.includesModifier(node.modifiers, ts.SyntaxKind.DeclareKeyword) 38 | ) { 39 | return; 40 | } 41 | 42 | context.report({ 43 | message: "preferModules", 44 | range: node.getChildAt(0), 45 | }); 46 | }, 47 | }; 48 | }, 49 | }); 50 | -------------------------------------------------------------------------------- /src/rules/utils/getConstrainedType.ts: -------------------------------------------------------------------------------- 1 | import * as ts from "typescript"; 2 | 3 | export function getConstrainedTypeAtLocation( 4 | node: ts.Node, 5 | typeChecker: ts.TypeChecker, 6 | ) { 7 | const type = typeChecker.getTypeAtLocation(node); 8 | return typeChecker.getBaseConstraintOfType(type) ?? type; 9 | } 10 | -------------------------------------------------------------------------------- /src/rules/utils/isTypeRecursive.ts: -------------------------------------------------------------------------------- 1 | import * as ts from "typescript"; 2 | 3 | export function isTypeRecursive( 4 | type: ts.Type, 5 | predicate: (t: ts.Type) => boolean, 6 | ): boolean { 7 | return type.isUnionOrIntersection() 8 | ? type.types.some((subType) => isTypeRecursive(subType, predicate)) 9 | : predicate(type); 10 | } 11 | -------------------------------------------------------------------------------- /src/testing/RuleTester.ts: -------------------------------------------------------------------------------- 1 | import assert from "node:assert"; 2 | 3 | import { AnyRuleDefinition } from "../types/rules.js"; 4 | import { AnyOptionalSchema, InferredObject } from "../types/shapes.js"; 5 | import { InvalidTestCase, ValidTestCase } from "../types/testing.js"; 6 | import { createReportSnapshot } from "./createReportSnapshot.js"; 7 | import { runTestCaseRule } from "./runTestCaseRule.js"; 8 | 9 | export interface RuleTesterOptions { 10 | describe?: TesterSetup; 11 | it?: TesterSetup; 12 | scope?: Record; 13 | } 14 | 15 | export interface TestCases { 16 | invalid: InvalidTestCase[]; 17 | valid: ValidTestCase[]; 18 | } 19 | 20 | export type TesterSetup = (description: string, setup: () => void) => void; 21 | 22 | export class RuleTester { 23 | #describe: TesterSetup; 24 | #it: TesterSetup; 25 | 26 | constructor({ describe, it, scope = globalThis }: RuleTesterOptions = {}) { 27 | this.#describe = defaultTo(describe, scope, "describe"); 28 | this.#it = defaultTo(it, scope, "it"); 29 | } 30 | 31 | describe( 32 | rule: AnyRuleDefinition, 33 | { invalid, valid }: TestCases>, 34 | ) { 35 | this.#describe(rule.about.id, () => { 36 | this.#describe("invalid", () => { 37 | for (const testCase of invalid) { 38 | this.#itInvalidCase(rule, testCase); 39 | } 40 | }); 41 | 42 | this.#describe("valid", () => { 43 | for (const testCase of valid) { 44 | this.#itValidCase(rule, testCase); 45 | } 46 | }); 47 | }); 48 | } 49 | 50 | #itInvalidCase( 51 | rule: AnyRuleDefinition, 52 | testCase: InvalidTestCase>, 53 | ) { 54 | this.#it(testCase.code, () => { 55 | const reports = runTestCaseRule( 56 | { 57 | // TODO: Figure out a way around the type assertion... 58 | options: (testCase.options ?? {}) as InferredObject, 59 | rule, 60 | }, 61 | testCase, 62 | ); 63 | const actual = createReportSnapshot(testCase.code, reports); 64 | 65 | assert.equal(actual, testCase.snapshot); 66 | }); 67 | } 68 | 69 | #itValidCase( 70 | rule: AnyRuleDefinition, 71 | testCaseRaw: ValidTestCase>, 72 | ) { 73 | const testCase = 74 | typeof testCaseRaw === "string" ? { code: testCaseRaw } : testCaseRaw; 75 | 76 | this.#it(testCase.code, () => { 77 | const reports = runTestCaseRule( 78 | { 79 | // TODO: Figure out a way around the type assertion... 80 | options: (testCase.options ?? {}) as InferredObject, 81 | rule, 82 | }, 83 | testCase, 84 | ); 85 | 86 | if (reports.length) { 87 | assert.deepStrictEqual( 88 | createReportSnapshot(testCase.code, reports), 89 | testCase.code, 90 | ); 91 | } 92 | }); 93 | } 94 | } 95 | 96 | function defaultTo( 97 | provided: TesterSetup | undefined, 98 | scope: Record, 99 | scopeKey: string, 100 | ): TesterSetup { 101 | if (provided) { 102 | return provided; 103 | } 104 | 105 | if (scopeKey in scope && typeof scope[scopeKey] === "function") { 106 | return scope[scopeKey] as TesterSetup; 107 | } 108 | 109 | throw new Error(`No ${scopeKey} function found`); 110 | } 111 | -------------------------------------------------------------------------------- /src/testing/createProgramSourceFile.ts: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair 2 | /* eslint-disable @typescript-eslint/no-non-null-assertion */ 3 | 4 | import { 5 | createFSBackedSystem, 6 | createVirtualTypeScriptEnvironment, 7 | } from "@typescript/vfs"; 8 | import { CachedFactory } from "cached-factory"; 9 | import path from "node:path"; 10 | import ts from "typescript"; 11 | 12 | const projectRoot = path.join(import.meta.dirname, "../.."); 13 | 14 | const environments = new CachedFactory((fileName: string) => { 15 | const system = createFSBackedSystem( 16 | new Map([[fileName, "// ..."]]), 17 | projectRoot, 18 | ts, 19 | ); 20 | 21 | return createVirtualTypeScriptEnvironment(system, [fileName], ts, { 22 | skipLibCheck: true, 23 | target: ts.ScriptTarget.ESNext, 24 | }); 25 | }); 26 | 27 | export function createProgramSourceFile(fileName: string, sourceText: string) { 28 | const environment = environments.get(fileName); 29 | environment.updateFile(fileName, sourceText); 30 | 31 | const sourceFile = environment.getSourceFile(fileName)!; 32 | const typeChecker = environment.languageService 33 | .getProgram()! 34 | .getTypeChecker(); 35 | 36 | return { sourceFile, typeChecker }; 37 | } 38 | -------------------------------------------------------------------------------- /src/testing/createReportSnapshot.ts: -------------------------------------------------------------------------------- 1 | import { NormalizedRuleReport } from "./runTestCaseRule.js"; 2 | 3 | export function createReportSnapshot( 4 | sourceText: string, 5 | reports: NormalizedRuleReport[], 6 | ) { 7 | let result = sourceText; 8 | 9 | for (const report of reports.toReversed()) { 10 | result = createReportSnapshotAt(result, report); 11 | } 12 | 13 | return result; 14 | } 15 | 16 | function createReportSnapshotAt( 17 | sourceText: string, 18 | report: NormalizedRuleReport, 19 | ) { 20 | const range = report.range; 21 | 22 | const lineEndIndex = ifNegative( 23 | sourceText.indexOf("\n", range.begin), 24 | sourceText.length, 25 | ); 26 | const lineStartIndex = ifNegative( 27 | sourceText.lastIndexOf("\n", range.begin), 28 | 0, 29 | ); 30 | 31 | const column = ifNegative(range.begin - lineStartIndex - 2, 0); 32 | const width = range.end - range.begin; 33 | 34 | const injectionPrefix = " ".repeat(column); 35 | const injectedLines = [ 36 | injectionPrefix + "~".repeat(width), 37 | injectionPrefix + report.message, 38 | ]; 39 | 40 | return [ 41 | sourceText.slice(0, lineEndIndex), 42 | ...injectedLines, 43 | sourceText.slice(lineEndIndex + 1), 44 | ].join("\n"); 45 | } 46 | 47 | function ifNegative(value: number, fallback: number) { 48 | return value < 0 ? fallback : value; 49 | } 50 | -------------------------------------------------------------------------------- /src/testing/normalizeRange.ts: -------------------------------------------------------------------------------- 1 | import type * as ts from "typescript"; 2 | 3 | import { ReportRange } from "../types/reports.js"; 4 | 5 | export function normalizeRange(range: ReportRange) { 6 | return isNode(range) 7 | ? { begin: range.getStart(), end: range.getEnd() } 8 | : range; 9 | } 10 | 11 | function isNode(value: unknown): value is ts.Node { 12 | return typeof value === "object" && value !== null && "kind" in value; 13 | } 14 | -------------------------------------------------------------------------------- /src/testing/runTestCaseRule.ts: -------------------------------------------------------------------------------- 1 | import * as ts from "typescript"; 2 | 3 | import { RuleConfiguration } from "../types/configurations.js"; 4 | import { ReportRangeObject, RuleReport } from "../types/reports.js"; 5 | import { AnyOptionalSchema } from "../types/shapes.js"; 6 | import { createProgramSourceFile } from "./createProgramSourceFile.js"; 7 | import { normalizeRange } from "./normalizeRange.js"; 8 | 9 | export interface NormalizedRuleReport { 10 | message: Message; 11 | range: ReportRangeObject; 12 | } 13 | 14 | export interface NormalizedTestCase { 15 | code: string; 16 | fileName?: string; 17 | } 18 | 19 | export function runTestCaseRule< 20 | OptionsSchema extends AnyOptionalSchema | undefined, 21 | >( 22 | { options, rule }: Required>, 23 | { code, fileName = "file.ts" }: NormalizedTestCase, 24 | ) { 25 | const { sourceFile, typeChecker } = createProgramSourceFile(fileName, code); 26 | 27 | const reports: NormalizedRuleReport[] = []; 28 | 29 | const context = { 30 | report(report: RuleReport) { 31 | reports.push({ 32 | message: rule.messages[report.message], 33 | range: normalizeRange(report.range), 34 | }); 35 | }, 36 | sourceFile, 37 | typeChecker, 38 | }; 39 | 40 | const visitors = rule.setup(context, options); 41 | 42 | if (!visitors) { 43 | return reports; 44 | } 45 | 46 | function visit(node: ts.Node) { 47 | // @ts-expect-error - TODO: Figure this out later... 48 | // eslint-disable-next-line @typescript-eslint/no-unsafe-call 49 | visitors[ts.SyntaxKind[node.kind]]?.(node); 50 | 51 | node.forEachChild(visit); 52 | } 53 | 54 | sourceFile.forEachChild(visit); 55 | 56 | return reports; 57 | } 58 | -------------------------------------------------------------------------------- /src/types/configurations.ts: -------------------------------------------------------------------------------- 1 | import { AnyRuleDefinition } from "./rules.js"; 2 | import { AnyOptionalSchema, InferredObject } from "./shapes.js"; 3 | 4 | export interface RuleConfiguration< 5 | OptionsSchema extends AnyOptionalSchema | undefined, 6 | > { 7 | options?: InferredObject; 8 | rule: AnyRuleDefinition; 9 | } 10 | -------------------------------------------------------------------------------- /src/types/context.ts: -------------------------------------------------------------------------------- 1 | import type * as ts from "typescript"; 2 | 3 | import { RuleReport } from "./reports.js"; 4 | 5 | export interface RuleContext { 6 | report: RuleReporter; 7 | sourceFile: ts.SourceFile; 8 | typeChecker: ts.TypeChecker; 9 | } 10 | 11 | export type RuleReporter = ( 12 | report: RuleReport, 13 | ) => void; 14 | -------------------------------------------------------------------------------- /src/types/nodes.ts: -------------------------------------------------------------------------------- 1 | import type * as ts from "typescript"; 2 | 3 | // TODO: Surely there's a better way to do this... 4 | // ...but I haven't checked how to do it without slow type operations. 5 | 6 | export type TSNode = TSNodesByName[keyof TSNodesByName]; 7 | 8 | export type TSNodeName = keyof TSNodesByName; 9 | 10 | export interface TSNodesByName { 11 | ArrayBindingPattern: ts.ArrayBindingPattern; 12 | ArrayLiteralExpression: ts.ArrayLiteralExpression; 13 | ArrowFunction: ts.ArrowFunction; 14 | AsExpression: ts.AsExpression; 15 | AwaitExpression: ts.AwaitExpression; 16 | BigIntLiteral: ts.BigIntLiteral; 17 | BinaryExpression: ts.BinaryExpression; 18 | BindingElement: ts.BindingElement; 19 | Block: ts.Block; 20 | BreakStatement: ts.BreakStatement; 21 | Bundle: ts.Bundle; 22 | CallExpression: ts.CallExpression; 23 | CaseBlock: ts.CaseBlock; 24 | CaseClause: ts.CaseClause; 25 | CatchClause: ts.CatchClause; 26 | ClassDeclaration: ts.ClassDeclaration; 27 | ClassExpression: ts.ClassExpression; 28 | ClassStaticBlockDeclaration: ts.ClassStaticBlockDeclaration; 29 | CommaListExpression: ts.CommaListExpression; 30 | ComputedPropertyName: ts.ComputedPropertyName; 31 | ConditionalExpression: ts.ConditionalExpression; 32 | ConditionalType: ts.ConditionalType; 33 | ContinueStatement: ts.ContinueStatement; 34 | DebuggerStatement: ts.DebuggerStatement; 35 | Decorator: ts.Decorator; 36 | DefaultClause: ts.DefaultClause; 37 | DeleteExpression: ts.DeleteExpression; 38 | DoStatement: ts.DoStatement; 39 | ElementAccessExpression: ts.ElementAccessExpression; 40 | EmptyStatement: ts.EmptyStatement; 41 | EnumDeclaration: ts.EnumDeclaration; 42 | EnumMember: ts.EnumMember; 43 | ExportAssignment: ts.ExportAssignment; 44 | ExportDeclaration: ts.ExportDeclaration; 45 | ExportSpecifier: ts.ExportSpecifier; 46 | ExpressionStatement: ts.ExpressionStatement; 47 | ExpressionWithTypeArguments: ts.ExpressionWithTypeArguments; 48 | ExternalModuleReference: ts.ExternalModuleReference; 49 | ForInStatement: ts.ForInStatement; 50 | ForOfStatement: ts.ForOfStatement; 51 | ForStatement: ts.ForStatement; 52 | FunctionDeclaration: ts.FunctionDeclaration; 53 | FunctionExpression: ts.FunctionExpression; 54 | HeritageClause: ts.HeritageClause; 55 | Identifier: ts.Identifier; 56 | IfStatement: ts.IfStatement; 57 | ImportAttribute: ts.ImportAttribute; 58 | ImportAttributes: ts.ImportAttributes; 59 | ImportClause: ts.ImportClause; 60 | ImportDeclaration: ts.ImportDeclaration; 61 | ImportEqualsDeclaration: ts.ImportEqualsDeclaration; 62 | ImportSpecifier: ts.ImportSpecifier; 63 | IndexedAccessType: ts.IndexedAccessType; 64 | InterfaceDeclaration: ts.InterfaceDeclaration; 65 | IntersectionType: ts.IntersectionType; 66 | JsxAttribute: ts.JsxAttribute; 67 | JsxAttributes: ts.JsxAttributes; 68 | JsxClosingElement: ts.JsxClosingElement; 69 | JsxClosingFragment: ts.JsxClosingFragment; 70 | JsxElement: ts.JsxElement; 71 | JsxExpression: ts.JsxExpression; 72 | JsxFragment: ts.JsxFragment; 73 | JsxNamespacedName: ts.JsxNamespacedName; 74 | JsxOpeningElement: ts.JsxOpeningElement; 75 | JsxOpeningFragment: ts.JsxOpeningFragment; 76 | JsxSelfClosingElement: ts.JsxSelfClosingElement; 77 | JsxSpreadAttribute: ts.JsxSpreadAttribute; 78 | JsxText: ts.JsxText; 79 | LabeledStatement: ts.LabeledStatement; 80 | LiteralType: ts.LiteralType; 81 | MappedTypeNode: ts.MappedTypeNode; 82 | MetaProperty: ts.MetaProperty; 83 | MethodDeclaration: ts.MethodDeclaration; 84 | MethodSignature: ts.MethodSignature; 85 | MissingDeclaration: ts.MissingDeclaration; 86 | ModuleBlock: ts.ModuleBlock; 87 | ModuleDeclaration: ts.ModuleDeclaration; 88 | NamedExports: ts.NamedExports; 89 | NamedImports: ts.NamedImports; 90 | NamedTupleMember: ts.NamedTupleMember; 91 | NamespaceExport: ts.NamespaceExport; 92 | NamespaceExportDeclaration: ts.NamespaceExportDeclaration; 93 | NamespaceImport: ts.NamespaceImport; 94 | NewExpression: ts.NewExpression; 95 | NonNullExpression: ts.NonNullExpression; 96 | NoSubstitutionTemplateLiteral: ts.NoSubstitutionTemplateLiteral; 97 | NotEmittedStatement: ts.NotEmittedStatement; 98 | NotEmittedTypeElement: ts.NotEmittedTypeElement; 99 | NumericLiteral: ts.NumericLiteral; 100 | ObjectBindingPattern: ts.ObjectBindingPattern; 101 | ObjectLiteralExpression: ts.ObjectLiteralExpression; 102 | OmittedExpression: ts.OmittedExpression; 103 | ParenthesizedExpression: ts.ParenthesizedExpression; 104 | PartiallyEmittedExpression: ts.PartiallyEmittedExpression; 105 | PostfixUnaryExpression: ts.PostfixUnaryExpression; 106 | PrefixUnaryExpression: ts.PrefixUnaryExpression; 107 | PrivateIdentifier: ts.PrivateIdentifier; 108 | PropertyAccessExpression: ts.PropertyAccessExpression; 109 | PropertyAssignment: ts.PropertyAssignment; 110 | PropertyDeclaration: ts.PropertyDeclaration; 111 | PropertySignature: ts.PropertySignature; 112 | QualifiedName: ts.QualifiedName; 113 | RegularExpressionLiteral: ts.RegularExpressionLiteral; 114 | ReturnStatement: ts.ReturnStatement; 115 | SatisfiesExpression: ts.SatisfiesExpression; 116 | SemicolonClassElement: ts.SemicolonClassElement; 117 | ShorthandPropertyAssignment: ts.ShorthandPropertyAssignment; 118 | SourceFile: ts.SourceFile; 119 | SpreadAssignment: ts.SpreadAssignment; 120 | SpreadElement: ts.SpreadElement; 121 | StringLiteral: ts.StringLiteral; 122 | SwitchStatement: ts.SwitchStatement; 123 | SyntaxList: ts.SyntaxList; 124 | SyntheticExpression: ts.SyntheticExpression; 125 | TaggedTemplateExpression: ts.TaggedTemplateExpression; 126 | TemplateExpression: ts.TemplateExpression; 127 | TemplateHead: ts.TemplateHead; 128 | TemplateLiteralType: ts.TemplateLiteralType; 129 | TemplateLiteralTypeSpan: ts.TemplateLiteralTypeSpan; 130 | TemplateMiddle: ts.TemplateMiddle; 131 | TemplateSpan: ts.TemplateSpan; 132 | TemplateTail: ts.TemplateTail; 133 | ThrowStatement: ts.ThrowStatement; 134 | TryStatement: ts.TryStatement; 135 | TupleType: ts.TupleType; 136 | TypeAliasDeclaration: ts.TypeAliasDeclaration; 137 | TypeOfExpression: ts.TypeOfExpression; 138 | TypeParameter: ts.TypeParameter; 139 | TypePredicate: ts.TypePredicate; 140 | TypeReference: ts.TypeReference; 141 | UnionType: ts.UnionType; 142 | VariableDeclaration: ts.VariableDeclaration; 143 | VariableDeclarationList: ts.VariableDeclarationList; 144 | VariableStatement: ts.VariableStatement; 145 | VoidExpression: ts.VoidExpression; 146 | WhileStatement: ts.WhileStatement; 147 | WithStatement: ts.WithStatement; 148 | YieldExpression: ts.YieldExpression; 149 | } 150 | -------------------------------------------------------------------------------- /src/types/plugins.ts: -------------------------------------------------------------------------------- 1 | import { RuleAbout, RuleDefinition } from "./rules.js"; 2 | import { AnyOptionalSchema, InferredObject } from "./shapes.js"; 3 | 4 | export interface Plugin< 5 | About extends RuleAbout, 6 | Rules extends RuleDefinition[], 7 | > { 8 | name: string; 9 | presets: PluginPresets; 10 | rules: PluginRulesFactory; 11 | } 12 | 13 | export type PluginPresets = Record< 14 | About["preset"] extends string ? About["preset"] : never, 15 | RuleDefinition[] 16 | >; 17 | 18 | export type PluginRulesFactory< 19 | Rules extends RuleDefinition< 20 | RuleAbout, 21 | string, 22 | AnyOptionalSchema | undefined 23 | >[], 24 | > = (rulesOptions: PluginRulesOptions) => Rules; 25 | 26 | export type PluginRulesOptions< 27 | Rules extends RuleDefinition< 28 | RuleAbout, 29 | string, 30 | AnyOptionalSchema | undefined 31 | >[], 32 | > = { 33 | [Rule in Rules[number] as Rule["about"]["id"]]?: Rule["options"] extends undefined 34 | ? boolean 35 | : boolean | InferredObject; 36 | }; 37 | -------------------------------------------------------------------------------- /src/types/reports.ts: -------------------------------------------------------------------------------- 1 | import type * as ts from "typescript"; 2 | 3 | export type ReportRange = ReportRangeObject | ts.Node; 4 | 5 | export interface ReportRangeObject { 6 | begin: number; 7 | end: number; 8 | } 9 | 10 | export interface RuleReport { 11 | message: Message; 12 | range: ReportRange; 13 | } 14 | -------------------------------------------------------------------------------- /src/types/rules.ts: -------------------------------------------------------------------------------- 1 | import { RuleContext } from "./context.js"; 2 | import { TSNode, TSNodeName, TSNodesByName } from "./nodes.js"; 3 | import { AnyOptionalSchema, InferredObject } from "./shapes.js"; 4 | 5 | export type AnyRuleDefinition< 6 | OptionsSchema extends AnyOptionalSchema | undefined = 7 | | AnyOptionalSchema 8 | | undefined, 9 | > = RuleDefinition; 10 | 11 | export interface RuleAbout { 12 | id: string; 13 | preset?: string; 14 | } 15 | 16 | export interface RuleDefinition< 17 | About extends RuleAbout, 18 | Message extends string, 19 | OptionsSchema extends AnyOptionalSchema | undefined, 20 | > { 21 | about: About; 22 | messages: Record; 23 | options?: OptionsSchema; 24 | setup: RuleSetup>; 25 | } 26 | 27 | export type RuleSetup = ( 28 | context: RuleContext, 29 | options: Options, 30 | ) => RuleVisitors | undefined; 31 | 32 | export type RuleVisitor = (node: Node) => void; 33 | 34 | export type RuleVisitors = { 35 | [Kind in TSNodeName]?: RuleVisitor; 36 | }; 37 | -------------------------------------------------------------------------------- /src/types/shapes.ts: -------------------------------------------------------------------------------- 1 | import { z } from "zod"; 2 | 3 | /** 4 | * Any object containing Zod schemas that are optional. 5 | * In other words, allows providing an empty object {} value. 6 | */ 7 | export type AnyOptionalSchema = Record< 8 | string, 9 | z.ZodDefault | z.ZodOptional 10 | >; 11 | 12 | /** 13 | * Given an object containing Zod schemas, produces the equivalent runtime type. 14 | * @example 15 | * ```ts 16 | * InferredObject<{ value: z.ZodNumber }> 17 | * ``` 18 | * is the same as: 19 | * ```ts 20 | * { value: number } 21 | * ``` 22 | */ 23 | export type InferredObject< 24 | OptionsSchema extends AnyOptionalSchema | undefined, 25 | > = OptionsSchema extends AnyOptionalSchema 26 | ? Partial>> 27 | : undefined; 28 | -------------------------------------------------------------------------------- /src/types/testing.ts: -------------------------------------------------------------------------------- 1 | export interface CommonTestCase { 2 | code: string; 3 | fileName?: string; 4 | options?: Options; 5 | } 6 | 7 | export interface InvalidTestCase 8 | extends CommonTestCase { 9 | output?: string; 10 | snapshot: string; 11 | } 12 | 13 | export type ValidTestCase = 14 | | string 15 | | ValidTestCaseObject; 16 | 17 | export type ValidTestCaseObject = 18 | CommonTestCase; 19 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "declaration": true, 4 | "declarationMap": true, 5 | "esModuleInterop": true, 6 | "lib": ["ES2024"], 7 | "module": "NodeNext", 8 | "moduleResolution": "NodeNext", 9 | "noEmit": true, 10 | "resolveJsonModule": true, 11 | "skipLibCheck": true, 12 | "strict": true, 13 | "target": "ES2024" 14 | }, 15 | "include": ["src"] 16 | } 17 | -------------------------------------------------------------------------------- /tsup.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from "tsup"; 2 | 3 | export default defineConfig({ 4 | bundle: false, 5 | clean: true, 6 | dts: true, 7 | entry: ["src/**/*.ts", "!src/**/*.test.*"], 8 | format: "esm", 9 | outDir: "lib", 10 | }); 11 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { defaultExclude, defineConfig } from "vitest/config"; 2 | 3 | export default defineConfig({ 4 | test: { 5 | clearMocks: true, 6 | coverage: { 7 | all: true, 8 | exclude: [...defaultExclude, "src/index.ts", "**/*.test-d.ts"], 9 | include: ["src"], 10 | reporter: ["html", "lcov"], 11 | }, 12 | exclude: ["lib", "node_modules"], 13 | setupFiles: ["console-fail-test/setup"], 14 | testTimeout: 10_000, 15 | }, 16 | }); 17 | --------------------------------------------------------------------------------